3

I have a list of groups populated from a database and use ngFor to iterate through in the html.

<mat-card  *ngFor="let group of groups" >
  <mat-card-title #group > {{group}}  </mat-card-title>
</mat-card>

I would like the #group to be the value of the group, not hardcoded. That way I can have another component to scroll to the different template variables.

How can I do this? Thanks.

Marcus Gallegos
  • 1,532
  • 1
  • 16
  • 31

1 Answers1

3

As per my knowelage template reference variables are uniquely scoped to the templates that they are defined in. And structural directive creates a nested template and therefore, introduces a separate scope, in your case mat-card-title.

So basically using group template reference variable inside <mat-card-title #group > will do in your case since it will hold unique scope for itself.

<mat-card  *ngFor="let group of groups" >
  <mat-card-title #group > {{group}}  </mat-card-title>
</mat-card>

For more details please refer answer by @yurzui here

Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
  • Let me expand, I want to be able to scroll to each of the groups. So sure the scope may not be conflicting but I do need the value of the group from the ngFor. – Marcus Gallegos Dec 27 '19 at 05:26
  • So cant you use a method inside the` {{group}} ` like this to get the group or something silmilar? – Selaka Nanayakkara Dec 27 '19 at 05:33
  • Always you can use a ViewChildren to get in a QueryList the elements -ende the Nativeelement and so, but as SelakaN say **inside** the *ngFor you can use **group** without conflict – Eliseo Dec 27 '19 at 07:27
  • Eliseo thank for the feedback. @Marcus Gallegos Appreciate if you can mark it as a correct answer or give an upvote if it helped you.. Thanks in advance – Selaka Nanayakkara Dec 27 '19 at 07:47