我在尝试对同一元素使用 Angular 的 *ngFor
和 *ngIf
时遇到问题。
当尝试遍历 *ngFor
中的集合时,该集合被视为 null
,因此在尝试访问其在模板中的属性时失败。
@Component({
selector: 'shell',
template: `
<h3>Shell</h3><button (click)="toggle()">Toggle!</button>
<div *ngIf="show" *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
`
})
export class ShellComponent implements OnInit {
public stuff:any[] = [];
public show:boolean = false;
constructor() {}
ngOnInit() {
this.stuff = [
{ name: 'abc', id: 1 },
{ name: 'huo', id: 2 },
{ name: 'bar', id: 3 },
{ name: 'foo', id: 4 },
{ name: 'thing', id: 5 },
{ name: 'other', id: 6 },
]
}
toggle() {
this.show = !this.show;
}
log(thing) {
console.log(thing);
}
}
我知道简单的解决方案是将 *ngIf
上移一个级别,但是对于像在 ul
中循环列表项这样的场景,我最终会选择如果集合为空,则为空 li
,或者我的 li
包含在冗余容器元素中。
此处的示例 plnkr .
注意控制台错误:
EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]
我做错了什么还是这是一个错误?
最佳答案
Angular v2 在同一元素上不支持多个结构指令。
作为解决方法,使用 <ng-container>
元素,允许您为每个结构指令使用单独的元素,但它未标记到 DOM。
<ng-container *ngIf="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</ng-container>
<ng-template>
(<template>
在 Angular v4 之前)允许做同样的事情,但使用不同的语法,这令人困惑并且不再推荐
<ng-template [ngIf]="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</ng-template>
关于angular - *ngIf 和 *ngFor 在同一元素上导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34657821/