【问题标题】:Ordering of custom item in *ngFor directive*ngFor 指令中自定义项目的排序
【发布时间】:2018-12-04 15:30:55
【问题描述】:

这是我的代码:

    <nav>
        <a [routerLink]="item.link"
            *ngFor="let item of links; let lastItem = last;"  
            *ngIf="!lastItem">
            {{item.title}}
        </a>
        <a (click)="clickOnCustomLink()">
            MY CUSTOM LINK
        </a>
        <a *ngIf="links" [routerLink]="links[links.length - 1].link">
            {{links[links.length - 1].title}}
        </a>
    </nav>

由于已知原因,我收到一个错误:

Can't have multiple template bindings on one element

有什么想法吗?

【问题讨论】:

标签: angular ngfor


【解决方案1】:

是的,你不能在一个角度元素上使用多个结构指令

改为使用 ng-container 运行 for 循环(ng-containers 不会在您的 DOM 中呈现):

<ng-container *ngFor="let item of links; let lastItem = last;"  >
    <a [routerLink]="item.link" *ngIf="!lastItem">
        {{item.title}}
    </a>
<ng-container>

【讨论】:

  • 你只需要交换指令;)
【解决方案2】:

不能在一个元素上添加两个结构指令。创建一个新的ng-container 并将ngFor 移动到该ngFor

   <ng-container [routerLink]="item.link" *ngFor="let item of links; let lastItem = last;" >
        <a [routerLink]="item.link" *ngIf="!lastItem">
               {{item.title}}
         </a> 
    </ng-container>

【讨论】:

    猜你喜欢
    • 2018-06-23
    • 2012-05-01
    • 2020-10-16
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2016-05-23
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多