我有一个组件,我想像这样使用
<comp [list]="['alpha', 'bravo', 'charlie']"></comp>
,即我希望它显示列表的内容。
组件的代码是
@Component({
selector: 'comp',
template: `
<ul>
<li *ngFor="item of decoratedList()">
{{ item.name }} - {{ item.foo }} - {{ item.bar }}
</li>
</ul>`
})
class Comp {
list: any[];
decoratedList(): any[] {
return this.list.map(item => ({
name: item,
foo: fooIt(item),
bar: barIt(item)
}));
}
}
此代码的问题是decoratedList
,因为它会在每次检查时返回一个新列表,因为它会使用map
,这会导致decoratedList() has Changed
- 类型错误。
处理这种模式的角度是什么意思?
答案 0 :(得分:1)
有两种方法:
decoratedList()
的结果分配给属性并将视图绑定到该属性@Component({
selector: 'comp',
template: `
<ul>
<li *ngFor="item of decoratedList">
{{ item.name }} - {{ item.foo }} - {{ item.bar }}
</li>
</ul>`
})
class Comp {
@Input() list: any[];
updateDecoratedList(): any[] {
this.decoratedList = this.list.map(item => ({
name: item,
foo: fooIt(item),
bar: barIt(item)
}));
}
// only called when a different list was passed, not when the content of the array changed
ngOnChanges() {
this.updateDecoratedList();
}
}
或使用IterableDiffers
和ngDoCheck
检查list
@Component({
selector: 'comp',
template: `
<ul>
<li *ngFor="item of decoratedList">
{{ item.name }} - {{ item.foo }} - {{ item.bar }}
</li>
</ul>`
})
class Comp {
@Input() list: any[];
differ: any;
constructor(differs: IterableDiffers) {
this.differ = differs.find([]).create(null);
}
updateDecoratedList(): any[] {
this.decoratedList = this.list.map(item => ({
name: item,
foo: fooIt(item),
bar: barIt(item)
}));
}
ngDoCheck() {
var changes = this.differ.diff(this.list);
if (changes) {
this.updateDecoratedList();
}
}
}
decoratedList()
将结果缓存到属性中,并且只有在某个相关值(list
)发生更改时才返回新值。对于此策略,还可以使用IterableDiffer
来检查list
内容的更改。