Angular 2 - 同一 DOM 元素上的两个结构指令 [英] Angular 2 - Two structural directives on the same DOM element
问题描述
在使用 Angular 2 时,我遇到了一个问题:显然我不能在同一个 DOM 元素上放置两个结构指令(ngFor
、ngIf
).
在 Angular 1 中,这曾经有效.对于示例:
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:
<div ng-repeat="item in items" ng-if="$even">{{item}}</div>
当我尝试使用 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"]
}
}
`,指令:[]})出口类应用{构造函数(){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.
但问题是我不想为此添加子元素.例如,如果它是表中的 <tr>
标签,那么在其中添加 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 仍处于测试阶段,但我想知道它是否是一个错误、一个功能,或者可能有一种未记录的方式来实现我想要的.
推荐答案
一个元素不支持两个结构指令.另请参阅 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.
这篇关于Angular 2 - 同一 DOM 元素上的两个结构指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!