*ngFor
Angular のと*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]
私は何か間違ったことをしていますか、それともこれはバグですか?