繁体   English   中英

Angular2中的装饰/计算数组

[英]Decorated/Computed arrays in Angular2

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

<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 -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,
          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();
      }
    }
} 
  • make decoratedList()将结果缓存在属性中,并且只有在某个相关值( list )发生更改时才返回新值。 对于此策略, IterableDiffer也可用于检查list内容的更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM