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

时间:2020-10-16 22:39:59

标签: angular angular-template-variable

我有一个巨型导航菜单,该菜单是通过遍历服务器的JSON响应而制成的。我想向第一个标签添加#first模板引用变量。 (这样,如果用户使用键盘选择mega nav的该部分,以便可以访问,则可以从其父组件访问该链接,以将焦点添加到该链接。)你如何做到的?

Button leadBtn = new Button();
leadBtn.addActionListener(e -> {
    //Handle action of the lead button
});

Button anotherBtn = new Button();
anotherBtn.addActionListener(e -> {
    //Handle action of the another button
});

Container myCont = new Container();
myCont.add(leadBtn);
myCont.add(anotherBtn);
myCont.setLeadComponent(leadBtn);
anotherBtn.setBlockedLead(true);

2 个答案:

答案 0 :(得分:1)

我不认为您可以动态添加它(您也不能使用指令来添加它),因此恐怕您需要创建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>

我有一种方法可以肯定有人会纠正我,但是我知道这就是方法。

答案 1 :(得分:0)

您需要写条件才能达到这种情况。 我更喜欢使用容器和模板来使代码更具可读性。 除了索引,您还可以检查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>
相关问题