angular2 – * ngIf和* ngFor在相同的元素导致错误
发布时间:2020-12-17 08:49:09 所属栏目:安全 来源:网络整理
导读:我有一个问题,试图使用Angular的* ngFor和* ngIf在同一个元素。 当试图循环遍历* ngFor中的集合时,集合被视为null,因此在尝试访问模板中的属性时失败。 @Component({ selector: 'shell',template: ` h3Shell/h3button (click)="toggle()"Toggle!/button d
我有一个问题,试图使用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 constructor) {} ngOnInit() { this.show = false; 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,我最终会有一个空的李,如果集合是空的,或我的lis包裹在冗余容器元素。 示例在这plnkr。 注意控制台错误: EXCEPTION:TypeError:无法在ShellComponent @ 5:12中的[{{thing.name}}中读取null的属性’name’ 我做错了什么,还是这是一个错误?
Angular2不支持同一个元素上的一个以上的结构指令。
作为解决方法,请使用< ng-container>元素,允许您为每个结构指令使用单独的元素,但它不会标记到DOM。 <ng-container *ngIf="show"> <div *ngFor="let thing of stuff"> {{log(thing)}} <span>{{thing.name}}</span> </div> </ng-container> < template>允许做同样的但使用不同的语法,这是混乱,不再推荐 <template [ngIf]="show"> <div *ngFor="let thing of stuff"> {{log(thing)}} <span>{{thing.name}}</span> </div> </template> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读