我在try 对同一元素使用Angular 的*ngFor
和*ngIf
时遇到问题.
当try 循环访问*ngFor
中的集合时,该集合被视为null
,因此在try 访问其在模板中的属性时失败.
@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
被包装在冗余的容器元素中.
举个例子.
请注意控制台错误:
EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]
是我做错了什么,还是这是个bug?