简体   繁体   English

如果第一个 Angular,则将模板引用变量属性添加到元素

[英]Add template reference variable attribute to element if first Angular

I have a mega nav menu that is made by looping through a JSON response from server.我有一个大型导航菜单,它是通过循环来自服务器的 JSON 响应制成的。 I want to add a #first template reference variable to the first a tag.我想将#first 模板引用变量添加到第一个 a 标签。 (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>

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.我不认为你可以动态添加它(你也不能用指令来做到这一点)所以恐怕你需要创建 2 个 html 标签。

<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.如果有办法,我相信有人会纠正我,但据我所知,这将是正确的方式。

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.您可以检查 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM