* ngIf和* ngFor对同一元素造成的错误 [英] *ngIf and *ngFor on same element causing error
问题描述
我在与试图用一个问题角度的 * ngFor
和 * ngIf
在相同的元素。
I'm having a problem with trying to use Angular's *ngFor
and *ngIf
on the same element.
当穿过 * ngFor
,收集被看作是空
,因此未能收集试图循环当试图访问它在模板的属性。
When trying to loop through the collection in the *ngFor
, the collection is seen as null
and consequently fails when trying to access it's properties in the template.
@Component({
selector: 'shell',
template: `
<h3>Shell</h3><button (click)="toggle()">Toggle!</button>
<div *ngIf="show" *ngFor="#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 $遍历列表项的情况C $ C>,我结束了一个空
里
如果集合是空的,还是我的里
ş包裹在冗余容器中的元素。
I know the easy solution is to move the *ngIf
up a level but for scenarios like looping over list items in a ul
, I'd end up with either an empty li
if the collection is empty, or my li
s wrapped in redundant container elements.
在这个例子 plnkr 。
请注意控制台错误:
异常:类型错误:无法读入空财产'名'[{{thing.name}}在ShellComponent @ 5:12]
我做得不对,或这是一个错误吗?
Am I doing something wrong or is this a bug?
推荐答案
由于@Zyzle提到的,这是不支持的。
As @Zyzle mentioned, this is not supported.
但随着
<ul *ngIf="show">
<li *ngFor="#thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</li>
</ul>
有没有空&LT;立GT;
元素时,列表是空的。即使是&LT; UL&GT;
元素不存在(如预期)
there are no empty <li>
elements when the list is empty. Even the <ul>
element does not exist (as expected).
当填充的列表中,有没有多余的容器元素
When the list is populated, there are no redundant container elements.
在他的评论中提到,@Zyzle的 GitHub的讨论也presents另一采用溶液&LT;模板&GT;
(下面我使用你原来的标记和划线;使用&LT; DIV&GT;
S)
The github discussion that @Zyzle mentioned in his comment also presents another solution using <template>
(below I'm using your original markup ‐ using <div>
s):
<template [ngIf]="show">
<div *ngFor="#thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</template>
此解决方案还没有引入任何额外/冗余的容器元素。
This solution also does not introduce any extra/redundant container elements.
这篇关于* ngIf和* ngFor对同一元素造成的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!