簡體   English   中英

動態組件的 Angular 2 OnPush 變化檢測

[英]Angular 2 OnPush change detection for dynamic components

我有一個 Angular 組件,它可以在自身內部動態創建各種其他類型的組件。 它通過OnChanges鈎子將自己的屬性綁定到子組件@Input屬性。

當子組件的更改檢測設置為默認值時,此綁定工作正常。 然后檢測新輸入並更新組件模板。

但是,更改檢測為 OnPush 時不起作用,則未檢測到更改。 我相信應該檢測到更改,因為一個新的不可變對象,一個字符串,被分配給組件@Input屬性。

這是一個展示的plunker: https ://plnkr.co/edit/0wHQghtww2HXVbC27bC1

我怎樣才能讓這個父到動態子屬性綁定與 ChangeDetectionStrategy.OnPush 一起使用?

OnPush 組件的可能解決方法是將 setter 與cdRef.markForCheck()一起使用:

更改檢測-onpush.component.ts

@Component({
  selector: 'app-change-detection-onpush',
  template: `
    <div>
      ChangeDetectionStrategy.OnPush: {{ message || '[blank]' }}
    </div>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChangeDetectionOnPushComponent implements IMyComponent {
  private _message: string;

  constructor(private cdRef: ChangeDetectorRef) {}

  set message(val: string) {
    this.cdRef.markForCheck();
    this._message = val;
  }

  get message() {
    return this._message;
  }
}

改良的Plunker

暫無
暫無

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

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