角度变化不会触发* ngFor component

时间:2018-04-15 16:39:08

标签: angular

我坚持以下内容:我在Angular 5中有一个父组件,它显示了cartProducts数组中每个元素的子组件。我的子组件接收cartProduct个对象作为输入。从BehaviorSubject对象接收我的cartProducts。每当我收到更新时,我都会更新我的数组。我期望我的所有子组件都会对我的阵列的更新作出反应,但这不会发生。我究竟做错了什么?

parent.component

constructor(private service:Service) {
    this.service.cpBehaviorSubject.subscribe({next: (v) => {
        console.log('Change triggerend in parent.');
        this.cartProducts = v;
      }});
}

parent.html

  <ng-template ngFor let-cp [ngForOf]="this.cartProducts">
    <app-child [cartProduct]="cp"></app-child>
  </ng-template>

child.component

  ngOnChanges() {
    console.log('Change triggered in child!');
  }

3 个答案:

答案 0 :(得分:0)

更改cartProducts以接收BehaviorSubject,然后在模板中使用async pipe

cartProducts$; 
constructor(private service:Service) {
   this.cartProducts$ = this.service.cpBehaviorSubject();
}

<ng-template ngFor let-cp [ngForOf]="this.cartProducts$ | async">
    <app-child [cartProduct]="cp"></app-child>
  </ng-template>

答案 1 :(得分:0)

您可以在父组件中尝试此操作:

constructor(private service:Service) {
  this.service.cpBehaviorSubject.subscribe((v) => {
    console.log('Change triggerend in parent.');
    this.cartProducts = v;
  });
}

答案 2 :(得分:0)

Angular不会对数组内容进行更改检测,只需对数组引用进行检测。

触发更改检测的最简单方法是在使用array.slice()更新数组内容后更新数组引用。

所以,例如,

myArray.push(foo);
myArray = myArray.slice();
相关问题