Angular 角度2变化检测-将数据推入阵列

Angular 角度2变化检测-将数据推入阵列,angular,Angular,我想将数据数组传递给子组件。根据子组件中的事件,数据可能会更改: HTML(父级): 数组中的新数据应在子组件中重新呈现。但Angular并没有重新定义这些变化 我找到了一个解决方案: 它会创建一个新数组 我的问题是:这是最好的方法还是有更好的方法?您可以在子组件中将subject/observates与markForCheck()一起使用 @Component({ selector: 'app-child', templateUrl: './child.component.html'

我想将数据数组传递给子组件。根据子组件中的事件,数据可能会更改:

HTML(父级):

数组中的新数据应在子组件中重新呈现。但Angular并没有重新定义这些变化

我找到了一个解决方案:

它会创建一个新数组


我的问题是:这是最好的方法还是有更好的方法?

您可以在子组件中将subject/observates与markForCheck()一起使用


@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent implements OnInit {
  @Input() data: Observable<any>;
  foods: string[] = [];

  constructor(private cd: ChangeDetectorRef) {}

  ngOnInit() {
    this.data.subscribe(food => {
      this.foods = [...this.foods, ...food];
      this.cd.markForCheck();
    });
  }
}

有关主题的更多详细信息,请签出如果将ChangeDetectionStrategy.OnPush放入子项,则需要使用
this.myArray=[…this.myArray,x]-更改数组-否则您无法进行任何更改


更好的选项是将Angular更新为8:)请参见,例如Angular的更改检测是否有更改?否。您是否在孩子身上设置了
OnPush
更改检测策略?那可能是从那里来的。但是要回答您的问题,使用不可变数据是一条可行之路。我在回答中用两个傻瓜的例子来补充我的评论我在回答中用两个傻瓜的例子来补充我的评论。如果选择change DetectionStrategy on Push,则需要更改数组或调用detectChanges
updateArray() {
  ...
  this.array.push(more data)
  ...
}
pushAndUpdate(x) {
  this.myArray = [...this.myArray, x];
}

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent implements OnInit {
  @Input() data: Observable<any>;
  foods: string[] = [];

  constructor(private cd: ChangeDetectorRef) {}

  ngOnInit() {
    this.data.subscribe(food => {
      this.foods = [...this.foods, ...food];
      this.cd.markForCheck();
    });
  }
}
subject = new Subject();
pushAndUpdate(x) {
  this.myArray.push(x);
  this.myArray = this.subject.next(this.myArray);
}
//hello, no change ChangeDetectionStrategy
@Component({
  selector: 'hello',
  template: `Hello <div *ngFor="let item of array">{{item}}</div>`,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent  {
  @Input() array: any[];
}

//hello2, ChangeDetectionStrategy
@Component({
  selector: 'hello2',
  template: `Hello2 <div *ngFor="let item of array">{{item}}</div>`,
  styles: [`h1 { font-family: Lato; }`],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent2  {
  @Input() array: any[];
}
<hello  [array]="array"></hello>
<hr/>
<hello2 [array]="array"></hello2>

<button (click)="click()">push</button>
<button (click)="click2()">CopyArray</button>


array=[1,2,3,4]
  click2(){
    this.array=[...this.array,1]
  }
  click(){
    this.array.push(1)
  }
  constructor(private cdr:ChangeDetectorRef){}
  click3(){
    this.array.push(1)
    this.cdr.detectChanges()
  }