Angular2中的装饰/计算数组

时间:2016-05-19 13:30:37

标签: design-patterns angular

我有一个组件,我想像这样使用

<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 - 类型错误。

处理这种模式的角度是什么意思?

1 个答案:

答案 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();
    }
} 

或使用IterableDiffersngDoCheck检查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内容的更改。