簡體   English   中英

Angular父子組件通信

[英]Angular communication between parent and child components

我有一個案例,我有一個父組件和 2 個子組件(基於 ng-select 的選擇組件)這個想法是,當我 select 和第一個 ng-select 中的項目時,同樣應該在第二個中禁用。 反之亦然。

在父我使用@ViewChildren 來查詢組件和設置禁用輸入屬性

在孩子們中,當我在 ng-select 中選擇和項目時,我會在父母中發出我需要的信息

在這種方法中,我然后找到正確的子組件並設置禁用的輸入屬性

const connectionSelector = this.connectionSelectors.find(connectionSelector => connectionSelector.source == false);
connectionSelector.disabledConnection = this.selectedSourceConnection;

在子組件中,我有 ngOnChanges 方法來檢查更改,但 disabledConnection 屬性沒有得到更新

它僅在我進行頁面加載時有效

父視圖:

<sc-connection-selector [default]="false" [source]="true" [quick]="false"
      [selectedConnection]="selectedSourceConnection"
      [disabledConnectionId]="disabledTargetConnectionId"
      (dataToEmit)="onValueChanged($event)">
</sc-connection-selector>

孩子:

<ng-select [items]="connections" bindLabel="userName"
    [placeholder]="'general.select-placeholder' | translate " 
    (change)="onConnectionChange()" 
    groupBy="type"
    dropdownPosition="bottom" 
    [(ngModel)]="selectedConnection">
    <ng-template ng-optgroup-tmp let-item="item">
      <b>{{item.type || 'Unnamed group'}}</b>
    </ng-template>
  </ng-select>

我在這里想念什么?

-賈尼

編輯:

您正在更新子組件上的值,而不是父組件上的值,如果發生 OnChanges 將觸發

指令的數據綁定屬性更改

這意味着,當父組件上的值發生變化時,它將觸發子組件上的 OnChanges。

為了獲得所需的行為,您應該將相關部分(在其中更新 disabled 屬性)從 OnChanges function 移動到 disabledConnectionId 的設置器,因此每次 (disabledConnectionId) 更改時,您都會更新下拉列表,這里是相關的代碼:

private currentDisabledConnectionId: Number;
@Input()
set disabledConnectionId(val: number) {
  if (this.currentDisabledConnectionId !== val) {
    this.currentDisabledConnectionId = val;
    this.setDisabledFields();
  }
}

private setDisabledFields() {
  this.connections.find(
    connection => connection.id == this.currentDisabledConnectionId
  ).disabled = true;
  console.log("connections: ", this.connections);
}

請注意,我已將輸入更改為 setter,並將屬性保存為私有字段。

另請注意,您在 stackblitz 上發布的內容不會刪除以前禁用的字段,只會添加新字段(我懷疑這是因為您只粘貼了一個可復制的示例)。

這是stackBlitz上的一個工作分叉示例

暫無
暫無

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

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