angular - 父子组件之间的角度通信
问题描述
我有一个案例,我有一个父组件和 2 个子组件(基于 ng-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 函数移动到 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上的一个工作分叉示例
推荐阅读
- bash - GNU 并行读取多个文件
- c# - 如何在 OnTicketReceived 期间重定向
- servicenow - Python:格式服务现在导出事件数据,特别是工作注释列,以确定事件违反或不违反状态
- c++ - 我应该按什么顺序从 MSVC 编译器读取构建错误?
- android - 交错水平Recyclerview Android,需要帮助
- android - Android SQLite 查询优化(ORM GreenDao)
- javascript - div的随机高度和颜色
- windows - 错误:无法连接到 Docker 守护程序 + WSL2
- redux - “DeepPartial
”类型的参数不可分配给“PreloadedState”类型的参数 - reactjs - Formik setFieldError 不显示消息或阻止提交