从父组件角度更新子组件输入

时间:2020-10-11 23:39:58

标签: javascript angular

如果将更改检测设置为OnPush,如何从父级启动子组件的更改检测?对象数组保留在父组件中,对于我而言,从父级开始更改子值(数组中的项)。

app.component.html:

<ul>
  <li *ngFor="let item of items">
    <button mat-button (click)="onClickMe(item)">Basic</button>
    <hello [item]=item></hello>
  </li>
</ul>

app.component.ts(相关部分):

export class AppComponent  {
  items: Item[] = [];
  constructor() {
    let i: number = 0;
    for (i=0; i<10; i++) {
      let tmps: ItemTmp[] = [];
      for (let j=0; j<10; j++) {
        tmps.push({
          value: ("tmp_" + j),
          selected: true
        });
      }
      this.items.push({
        id: i,
        name: ("item_" + i),
        tmps: tmps
      });
    }
  }

  onClickMe(item: Item): void {
    item.tmps[0].selected = !item.tmps[0].selected;
    console.log(item.tmps[0].selected);
  }
}

hello.component.ts:

@Component({
  selector: 'hello',
  template: `
    <h1>{{item.id}} - {{item.name}}</h1>
    <li *ngFor="let tmp of item.tmps">
    {{tmp.value}} - {{tmp.selected}}
    </li>
  `,
  styles: [`h1 { font-family: Lato; }`],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent {

  @Input() item: Item;

}

我创建了一个示例项目来显示我的问题。

https://stackblitz.com/edit/angular-ivy-7v5pef?file=src/app/app.component.html

在此示例中,我需要子对象中的值在屏幕上更新。我可以在控制台中看到父级数组中的对象正在按我的期望进行更新。但是子组件没有改变。

1 个答案:

答案 0 :(得分:1)

OnPush表示检查引用,而不是值。除非父母开始将item的新引用传递给孩子,否则那里没有任何跟踪。解决此问题的一种方法是更改​​onClickMe函数,以便与其修改item value ,而开始修改items集合,然后在其中注入新对象。像这样:

<button mat-button (click)="onClickMe(i)">Basic</button>

// in .ts
onClickMe(i: number): void {
  const item = this.items[i];
  this.items[i] = { ...item };
  // you can do this in-place now, as a new reference is already created
  this.items[i].tmps[0].selected = !this.items[i].tmps[0].selected;
  console.log(item.tmps[0].selected);
}
相关问题