點擊切換數據流的傳遞方式 angular 自上而下傳遞無返回值的函數

遵循一個原則:Angular的數據流是自頂而下,從父組件到子組件單向流動。單向數據流向保證了高效、可預測的變化檢測。儘管檢查了父組件之後,子組件可能會改變父組件的數據使得父組件需要再次被檢查,這是不被推薦的數據處理方式。

從父組件【input】進去的數據, 如果在子組件修改的話,父組件訪問到的也是改變後的數據,而不是修改前。

思想:自上而下傳遞無返回值的函數,賦予下層修改上層值的方法,即可在上層維護下層組件的狀態信息。每層只需知道子組件本身需更新的信息


現有1個父組件F,2個子組件S1, S2。當點擊S1的卡片,S2要知道被選中,顯示對應的頁面。此時應在父組件維護數據信息,把修改的方法通過[input]傳給子組件S1。而不是:被點擊的S1向上拋事件給父組件,這種反向數據流的模式本身是不太好的。

update = (value: any) => {
    this.data = {...this.data, mid: value};
  }
// 把update方法input給子組件

 

修改前代碼如下:

S1 html:

<div
  class="item"
  *ngFor="let item of petItems"
  fxLayout="row"
  fxLayoutAlign="start center"
  (click)="petCardClick(item)"
  [ngClass]="item === selectedItem ? 'currentDisplay' : ''"
>
  <div fxFlex="12"></div>
  {{ item }}
</div>

 

S1 ts:

export const enum PETMaintenanceItems {
  DelayCalibration = 'Delay Calibration',
  GainCalibration = 'Gain Calibration'
}
  petItems: PETMaintenanceType[] = [
    { PETName: PETMaintenanceItems.DelayCalibration },
    { PETName: PETMaintenanceItems.GainCalibration }
  ];

petCardClick(id: any) {
    this.maintenanceCardClick.emit(id);
    this.selectedItem = id;
  }

M html:

<app-maintenance-dashboard
      (maintenanceCardClick)="maintenanceCardClicked($event)"
    ></app-maintenance-dashboard>

M ts:

maintenanceItems?: string;
maintenanceCardClicked(id: string) {
   this.maintenanceItems = id;
   console.log(this.maintenanceItems);
  } 

 

修改後代碼如下:

M html:

<app-maintenance-dashboard
      [ctItems]="ctMaintenanceItems"
      [petItems]="petMaintenanceItems"
      [itemClicked]="itemMaintenanceClicked"
    ></app-maintenance-dashboard>

 <ng-container [ngSwitch]="currentMaintenance">
      <ng-container *ngSwitchCase="'Fast Calibration'">
</ng-container>
</ng-container

M ts:

  currentMaintenance?: string;
  itemMaintenanceClicked = (id: any) => {
    this.currentMaintenance = id;
  };

 S1 ts:

@Input() itemClicked: any;

ctCardClick(id: any) {
    this.itemClicked(id);
    // this.maintenanceCardClick.emit(id);
    this.selectedItem = id;
  }

S1 html:

<div
  class="item"
  *ngFor="let item of ctItems"
  fxLayout="row"
  fxLayoutAlign="start center"
  (click)="ctCardClick(item)"
  [ngClass]="item === selectedItem ? 'currentDisplay' : ''"
>
  <div fxFlex="12"></div>
  {{ item }}
</div>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章