1

In my Angular application I came across a scenario in which I have to show an activity history for a user as in Facebook's activity log.

The activity templates may be of different types like:

  1. KLM creates subOrder 10463 from Order 2569
  2. XYZ deleted subOrder 1046
  3. ABC commented on Order 2569

and so on.

The bold text will be a link which navigates the user to the user's corresponding profile or particular subOrder or Order.

In the TypeScript file I created the link for users/actors like KLM, ABC or XYZ as follows:

const tempActorLink = '<a href=/user-profile/' + history.actorId + '/' + history.actorName + '>' + history.actorName + '</a>';

Then I replace the {actor} string in history with the created link as follows:

history.activity = history.activity.replace('{actor}', tempActorLink);

I did the same when creating Order and subOrder links.

I used innerHTML to add it to the DOM as shown below:

<span innerHTML="{{history.activity}}"></span>

Due to the use of href the page reloads, which is undesirable.

I tried to use the routerLink directive as shown in the TypeScript code below:

const tempActorLink = '<a [router-link]=\"[\'/user-profile/' + history.actorId + '/' + history.actorName + '\']\">' + history.actorName + '</a>';

I can't see the routerLink directive in the created DOM code.

Please help me out to dynamically add the links in the DOM with the routerLink directive or some other approach that has the desired effect.

Johannes
  • 828
  • 12
  • 29
Meenakshi Kumari
  • 120
  • 1
  • 11
  • 2
    You can't add anything Angular-specific to a template dynamically. The only way to do that is to create and compile a component that contains that markup in the template at runtime. What you can do is to use `querySelector(...)` to query the dynamically added HTML, add a click handler `addEventListener(...)` and assign a callback that calls `this.router.navigate(...)` – Günter Zöchbauer Aug 16 '17 at 08:06
  • 2
    you cannot add the routerlink directive using this way as innerhtml , you need to follow the way as @GünterZöchbauer pointed out – Rahul Singh Aug 16 '17 at 08:06

0 Answers0