angular - 无法在 2 个或更多组件实例之间共享一个表单控件实例
问题描述
我有 2 个电话号码字段应该同步,即更改第一个电话号码字段应该更新第二个电话号码字段,反之亦然。
我曾尝试共享一个 fromControl 实例 b/w 那些不起作用的 2 个电话号码字段组件。 https://stackblitz.com/edit/angular-ha16re?file=app/form-field-custom-control-example.html
我也尝试过使用 ngModel 也没有用。
<mat-form-field>
<example-tel-input
placeholder="Phone number"
[formControl]="selectedTel"></example-tel-input>
</mat-form-field>
<mat-form-field>
<example-tel-input
placeholder="Phone number copy"
[formControl]="selectedTel"></example-tel-input>
</mat-form-field>
selectedTel = new FormControl();
constructor() {
this.selectedTel.valueChanges.subscribe(newVal => {
console.log('selected tel number is:', newVal);
});
我期望这两个字段应该是同步的。
解决方案
尝试将您的订阅更改为:
this.selectedTel.valueChanges.subscribe(newVal => {
this.selectedTel.setValue(newVal, {emitEvent:false});
console.log('selected tel number is:', newVal);
});
推荐阅读
- android - 在 dart 中隐藏和显示小部件
- maven - 使用 swagger-maven-plugin 3.1.7 生成的空 swagger.json
- python - Tkinter 窗口未打开且小部件未显示
- javascript - 如何在jquery中找到一个类时空
- mysql - 将数据从 rest api 推送到 sql 数据库的最佳方法是什么?
- javascript - 弹出窗口和停止计数器需要 JavaScript 帮助
- javascript - JS 表达式,用于根据先前响应输出中的多个变量计算和设置输入值
- node.js - 使用带有过滤器的 Mongoose .find() 调用 API 不返回任何内容?
- arrays - 如何访问深层嵌套的 json 即转换为 json 的肥皂 xml 响应
- python - 在 python 上做语音助手