簡體   English   中英

動態組件中的角度變化檢測

[英]Angular Change Detection in a Dynamic Component

我在 Angular 中動態添加的組件中遇到更改檢測問題。

我在下面添加了一個完整的Plunker鏈接。

該組件有兩個屬性( gridmessage ),兩個屬性都有 setter 和 getter。

grid屬性基於“類型”接口IGrid ,並且message是一個string 動態創建組件並添加到父組件時,網格消息都會添加到組件實例中。

網格消息的設置器調用一個名為consolelog的函數。

根據對各自輸入的更改,網格消息的更改檢測似乎都在起作用。

我遇到的問題是,consolelog函數的調用是否正確的消息二傳手,但是consolelog功能沒有被正確稱為網格中的二傳手。

模板:

<div>
  <div><b>grid.pinnedColumnHeaders</b></div> 
  input: 
  <input type="checkbox" 
    name="grid.pinnedColumnHeaders" 
    [(ngModel)]="grid.pinnedColumnHeaders">
</div>
<div>
  value: {{ grid.pinnedColumnHeaders || '[blank]' }}
</div>
<hr>
<div>
  <div><b>message:</b></div>
  input: <input type="text" name="message" 
  [(ngModel)]="message">
</div>
<div>
  value: {{ message || '[blank]' }}
</div>

成分:

@Component({
  selector: 'app-change-detection-onpush',
  template: `...`,
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class ChangeDetectionOnPushComponent implements IPage {
    private _message: string;
    private _grid: IGrid;

    ngAfterViewInit() {

    }

    constructor(private cdRef: ChangeDetectorRef) { }

    set grid(val: string) {
      this.cdRef.markForCheck();
      this.logconsole();
      this._grid = val;
    }

    get grid() {
      return this._grid;
    }

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

    get message() {
      return this._message;
    }

   logconsole(){
     console.log('test');
   }
 }    

完整的 Plunker: https ://next.plnkr.co/edit/t1xK698tsJDnzS5E ? open = lib%2Fapp.ts & deferRun =1

根據您在評論中所說的,我對您可能正在尋找的方法還有兩個猜測:

  1. 是@ngrx/store 方法。 (這是有據可查的)
  2. 是在你的服務中讓grid成為私有的Subject (或來自'rxjs'的BehaviorSubject),並在服務中做setter和getter。

     import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; @Injectable() export class MyService{ private grid: Subject<IGrid> = new Subject<IGrid>(); getGrid(): Observable<IGrid> { return this.grid.asObservable(); }; setGrid(values: IGrid): void { this.grid.next(values); } }

    然后在您的任何組件中(注意,不要忘記unsubscribe ngOnDestroy()):

     export class MyComponent { grid: IGrid; constructor(private service: Myservice){} getGrid(): void { this.service.getGrid().subscribe((grid: IGrid) => this.grid = grid); } setGrid(gridData: IGrid): void { this.service.setGrid(gridData); } }

盡管如此,在這種方法中,您必須按照上面的建議處理輸入更改,因為如果對象的一部分發生更改,ngModel 將不會調用 setter。 但在這種情況下,您可以確定,如果您在一處進行更改,所有訂閱者都會收到更改。

暫無
暫無

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

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