*ngif和*ngf對同一元素造成錯誤我不想用角的*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封裝在冗余容器元素中。這個例子普朗克.注意控制臺錯誤:EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]我是做錯什么了還是這是個蟲子?
3 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
[hidden]
*ngIf
<div [hidden]="!show" *ngFor="let thing of stuff">
*ngIf
[hidden]
CSS
添加回答
舉報
0/150
提交
取消