繁体   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