angular2在一个元素上不能有多个模板绑定 [英] angular2 Can't have multiple template bindings on one element
问题描述
我有这个angular2模板:
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>
我收到以下错误:
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中的问题是什么它应该有效。不是吗?
what's the problem I put *ngIf and *ngFor in defferent html elements. It should work. no?
和:
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 = []
的情况。我该怎么办呢?
*ngIf="alerts.length > 0
to avoid cases of alert = []
. How can i fix it otherwise?
推荐答案
*
in * ngFor
使Angular添加< template>
标记。在< template>
标记上,这没有意义,因此这里的结构指令具有不同的语法。
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">
因为不同地方几乎相同的语法引起了一些混乱,Angular团队最近推出了
Because different syntax for almost the same on different places caused quite some confusion, the Angular team recently introduced
<ng-container>
行为类似于< template>
标签(未添加到DOM)但允许更常见的语法
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>
这篇关于angular2在一个元素上不能有多个模板绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!