*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
提交
取消