我有一个组件,我想这样使用
<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) })); } }
这段代码的问题是DecorativeList,因为它每次检查都会返回一个新列表,因为它使用了map,这导致了decoratedList()出现了Changed-type错误.
处理这种模式的角度是什么意识形态的方法?
解决方法
有两种方法:
>将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,bar: barIt(item) })); } // only called when a different list was passed,not when the content of the array changed ngOnChanges() { this.updateDecoratedList(); } }
或者使用IterableDiffers和ngDoCheck来检查列表内容的变化
@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,bar: barIt(item) })); } ngDoCheck() { var changes = this.differ.diff(this.list); if (changes) { this.updateDecoratedList(); } } }
> make decoratedList()将结果缓存在属性中,并且只有在某个相关值(列表)发生更改时才返回新值.对于此策略,IterableDiffer也可用于检查列表内容的更改.