加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

设计模式 – Angular2中的装饰/计算数组

发布时间:2020-12-17 17:06:51 所属栏目:安全 来源:网络整理
导读:我有一个组件,我想这样使用 comp [list]="['alpha','bravo','charlie']"/comp 即,我希望它显示列表的内容. 组件的代码是 @Component({ selector: 'comp',template: ` ul li *ngFor="item of decoratedList()" {{ item.name }} - {{ item.foo }} - {{ item.ba
我有一个组件,我想这样使用

<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也可用于检查列表内容的更改.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读