angular2在一个元素上不能有多个模板绑定

时间:2016-10-19 08:29:09

标签: javascript angular

我有这个angular2模板:

<template *ngIf="alerts.length > 0">
<alert *ngFor="let alert of alerts;let i = index" [type]="alert.type" dismissible="true" (close)="closeAlert(i)">
  {{ alert?.msg }}
</alert>
  </template>

我收到这些错误:

zone.js:461 Unhandled Promise rejection: Template parse errors:
Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * (" </div>
  <div *ngSwitchCase="false" class="container p-t-10">
    <alert *ngIf="alerts.length > 0" [ERROR ->]*ngFor="let alert of alerts;let i = index" [type]="alert.type" dismissible="true" (close)="closeAlert"): b@5:37

我把* ngIf和* ngFor放在不同的html元素中的问题是什么。它应该工作。没有?

Can't bind to 'type' since it isn't a known property of 'alert'. (""container p-t-10">
    <alert *ngIf="alerts.length > 0" *ngFor="let alert of alerts;let i = index" [ERROR ->][type]="alert.type" dismissible="true" (close)="closeAlert(i)">
      {{ alert?.msg }}
    </alert>
"): b@5:80

我添加了

*ngIf="alerts.length > 0以避免alert = []的案例。我怎么能解决它呢?

2 个答案:

答案 0 :(得分:16)

*中的*ngFor会使Angular添加<template>标记。在<template>标签上,这没有意义,因此这里的结构指令具有不同的语法。

<template ngFor [ngForOf]="alerts" let-alert let-i="index">

因为在不同地方几乎相同的不同语法引起了一些混乱,Angular团队最近引入了

<ng-container>

行为类似于<template>标记(未添加到DOM)但允许更常见的语法

<ng-container *ngIf="alerts.length > 0">
  <alert *ngFor="let alert of alerts;let i = index" [type]="alert.type" dismissible="true" (close)="closeAlert(i)">
    {{ alert?.msg }}
  </alert>
</ng-container>

答案 1 :(得分:0)

在这种情况下,您应该使用<ng-container>。例如:

<ng-container *ngIf="totalItems > 0">
      <tr *ngFor="let item of outputs| paginate: { id:'ab', itemsPerPage: pageSize, currentPage: currentPage, totalItems: totalItems  }; let $index = index">
        <td>{{item.x}}</td>
        <td>{{item.y | date: 'MMMM d, y, h:mm:ss a' }}</td>
        <td>{{item.z}}</td>
        <td>{{item.r}}</td>

      </tr>
    </ng-container>
    <ng-container *ngIf="totalItems > 10">
      <tr *ngFor="let item of outputs| paginate: { id:'aabbbbbbbbb', itemsPerPage: pageSize, currentPage: currentPage, totalItems: totalItems  }; let $index = index">
            <td>{{item.x}}</td>
        <td>{{item.y | date: 'MMMM d, y, h:mm:ss a' }}</td>
        <td>{{item.z}}</td>
        <td>{{item.r}}</td>
      </tr>
    </ng-container>