【发布时间】:2016-04-12 00:01:35
【问题描述】:
我在尝试在同一元素上使用 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,或者我的lis 包裹在冗余容器元素中。
plnkr 的示例。
注意控制台错误:
EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]
是我做错了什么还是这是一个错误?
【问题讨论】:
-
stackoverflow.com/questions/40529537/… 我会选择 ng-container
标签: angular ngfor angular-ng-if