0

I have a mega nav menu that is made by looping through a JSON response from server. I want to add a #first template reference variable to the first a tag. (This is so that I can access it from its parent component to add focus to that link if a user uses the keyboard to select that part of mega nav; to make it accessible.) Below isn't working. How do you do this?

  <li *ngFor="let item of subMenu.items; let itemIndex=index;">
    <a (click)="linkMegaClicked($event)"
      [routerLink]="item.url"
      [#first]="itemIndex == 0"
      [innerHtml]="item.link_text">
    </a>
  </li>
Andrew Koper
  • 6,481
  • 6
  • 42
  • 50

2 Answers2

0

I Don't think you can add this dynamically (you can't do this with directives either) so i'm afraid you'll need to create 2 html tags.

<li *ngFor="let item of subMenu.items; let i = index;">
  <a
    #first
    *ngIf="i === 0"
    [routerLink]="item.url"
    [innerHtml]="item.link_text"
    (click)="linkMegaClicked($event)">
  </a>

  <a
    *ngIf="i !== 0"
    [routerLink]="item.url"
    [innerHtml]="item.link_text"
    (click)="linkMegaClicked($event)">
  </a>
</li>

I'f there is a way i'm sure somebody will correct me but for what I know this will be the way.

  • 1
    Does this answer your question https://stackoverflow.com/questions/44440879/dynamic-template-reference-variable-inside-ngfor-angular-9 ? – Owen Kelvin Oct 17 '20 at 03:45
  • This is the same behavior for NgModel. – JWP Oct 17 '20 at 03:54
  • @OwenKelvin, it's sort of the answer. The ViewChildren can work and could be OP's solution. But it's still not a conditional directive. Anyway, thanks for the link! – Lars Vanderheydt Oct 17 '20 at 10:34
0

You will need to write condition to acheive this case. I prefer to use container and template to make code more readable. Instead of index you can check for first attr of ngFor.

<li *ngFor="let item of subMenu.items; first as isFirst">
  <ng-container *ngIf="isFirst; else otherItem">
    <a #first
       [routerLink]="item.url"
       [innerHtml]="item.link_text"
       (click)="linkMegaClicked($event)">
    </a>
  </ng-container>
  <ng-template #otherItem>
    <a *ngIf="i !== 0"
       [routerLink]="item.url"
       [innerHtml]="item.link_text"
       (click)="linkMegaClicked($event)">
    </a>
  </ng-template>
</li>
Rashmi Kumari
  • 520
  • 4
  • 15