0

I am using Angular 2 and looking to set-up a page where the contents are displayed through an *ngFor loop, and the body is displayed through a separate div. These use interpolation to display the objects relevant properties. I would like the content to link to the relevant div in the body.

To display the contents in the left hand side:

<div class = "contents">
  <div *ngFor = "let disp of content">
    {{disp.heading}}
  </div>
</div>

To display the article on the right hand side

<div *ngFor="let disp of content>
  {{disp.header}}
  {{disp.body}}
<div>

This is similar to the query here Angular2 Routing with Hashtag to page anchor

However, as it is in an *ngFor loop dependent on content, abd uses interpolation, I cannot see a way to identify different divs within the loops as these are provided dynamically.

1 Answers1

3

However, as it is in an *ngFor loop dependent on content

Not necessarily, You can get the current index of a *ngFor in angular using the predefined index variable

So, we can set the links to point to href=#content{{i}} which is href=#content0 for the first element, href=#content1 for the second element and so on,

<div *ngFor="let disp of content; let i=index">
    <a href="#content{{i}}"> {{disp.heading}} </a>
</div>

Then we can create the content divs using the same idea,

<div *ngFor="let disp of content; let i=index" id="content{{i}}">
    <h1> {{disp.header}} </h1>
    <p> {{disp.body}} </p>
</div>

so the first div will have an id #content0, the second one #content1 and so on,

working example

Hope this helps

cyberpirate92
  • 3,076
  • 4
  • 28
  • 46