angular2 Can't have multiple template bindings

2020-04-02 06:32发布

问题:

I have this angular2 template:

<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>

I get these errors:

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

what's the problem I put *ngIf and *ngFor in defferent html elements. It should work. no?

and:

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

I added the

*ngIf="alerts.length > 0 to avoid cases of alert = []. How can i fix it otherwise?

回答1:

The * in *ngFor makes Angular to add a <template> tag. On a <template> tag this doesn't make sense and therefore here structural directives have a different syntax.

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

Because different syntax for almost the same on different places caused quite some confusion, the Angular team recently introduced

<ng-container>

that behaves similar to the <template> tag (is not added to the DOM) but allows the more common syntax

<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>


回答2:

You should use <ng-container> for this case. As a example:

<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>