簡體   English   中英

來自父組件的角度更新子組件輸入

[英]Angular updating child component input from parent component

如果更改檢測設置為 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);
  }
}

你好.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

在這個例子中,我需要在屏幕上更新子對象中的值。 我可以在控制台中看到父級數組中的對象正在按照我的預期更新。 但是子組件沒有改變。

OnPush 意味着檢查引用,而不是值。 除非父項開始將新的item引用傳遞給子項,否則那里不會跟蹤任何內容。 處理這個問題的一種方法是更改onClickMe函數,這樣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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM