This question already has an answer here:
这个问题在这里已有答案:
- *ngIf and *ngFor on same element causing error 11 answers
* ngIf和* ngFor在同一元素上导致错误11答案
While playing around with Angular 2, I've encountered a problem: apparently I can't put two structural directives (ngFor
, ngIf
) on the same DOM element.
In Angular 1 this used to work. For example:
在玩Angular 2时,我遇到了一个问题:显然我不能在同一个DOM元素上放置两个结构指令(ngFor,ngIf)。在Angular 1中,这曾经起作用。例如:
<div ng-repeat="item in items" ng-if="$even">{{item}}</div>
When I try something similar with Angular 2:
当我尝试与Angular 2类似的东西时:
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<div *ngFor="#item of items; #e = even" *ngIf="e">{{item}}</div>
</div>
`,
directives: []
})
export class App {
constructor() {
this.items = ["a","b","c"]
}
}
Nothing happens. Not even an error.
什么都没发生。甚至没有错误。
If I put the ngIf
directive on a child element, it works:
如果我将ngIf指令放在子元素上,它可以工作:
<div *ngFor="#item of items; #e = even"><div *ngIf="e">{{item}}</div></div>
But the problem is I don't want to add a child element just for that. If, for example, it's a <tr>
tag inside a table, then adding a div
inside will make the DOM weird.
但问题是我不想为此添加子元素。例如,如果它是表中的标记,那么在内部添加div将使DOM变得怪异。
I know Angular 2 is still in beta, but I'm wondering if it's a bug, a feature, or maybe there's an undocumented way to achieve what I want.
我知道Angular 2仍处于测试阶段,但我想知道它是否是一个bug,一个功能,或者可能是一种无证的方式来实现我想要的。
1 个解决方案
#1
4
Two structural directives are not supported on one element. See also https://github.com/angular/angular/issues/4792
一个元素不支持两个结构指令。另见https://github.com/angular/angular/issues/4792
Instead nest them while using template syntax for the outer one and micro syntax for the inner one.
而是在使用外部模板语法和内部模板语法时嵌套它们。
#1
4
Two structural directives are not supported on one element. See also https://github.com/angular/angular/issues/4792
一个元素不支持两个结构指令。另见https://github.com/angular/angular/issues/4792
Instead nest them while using template syntax for the outer one and micro syntax for the inner one.
而是在使用外部模板语法和内部模板语法时嵌套它们。