Angular 将控件绑定到多个输入的反应式表单不会刷新其他表单

Angular Reactive Forms binding a control to multiple inputs doesn't refresh the others

当我使用响应式表单并尝试在多个输入中访问同一控件时,它看起来只是一种单向数据绑定(输入到模型)。 如果我编辑一个输入,它会正确更新模型,但它也不会刷新其他输入。

<input type="text" formControlName="test" id="in1">
<input type="text" formControlName="test" id="in2">

我的工作是将以下行添加到两个输入:

(change)="form.controls.test.setValue(form.controls.test.value)

但老实说,这看起来是一个非常糟糕的解决方案。我在这里做错了什么吗?存档的正确方法是什么?

https://plnkr.co/edit/yALzCIHgOA463OvGi5rP

您可以使用 ngModel:

<div>
    <form [formGroup]="form">
        <h2>Test = {{form?.controls.test.value}}</h2>
        1. <input type="text" formControlName="test" [(ngModel)]="test"> 
    2. <input type="text" formControlName="test" [(ngModel)]="test"> 
    3.
        <button type="button" (click)="form.controls.test.setValue('manual')">change with setValue</button>
    </form>
</div>

The two-way binding syntax is really just syntactic sugar for a property binding and an event binding

例如:

<app-sizer [(size)]="fontSizePx"></app-sizer> 

等于:

<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>

CODE EXAMPLE

我不确定为什么您需要 2 个具有相同 formControlName 的字段,但解决方案可能是 - 创建自定义 angular 元素。

@Component({
  selector: 'custom-element',
  templateUrl: `
    <input type="text" [(ngModel)]="value">
    <input type="text" [(ngModel)]="value">
  `,
  styleUrls: ['./custom-element.component.css']
})
export class CustomElementComponent implements ControlValueAccessor

@Input() value: any 

writeValue(value: any) {
  // Some if statements
  this.value = value;
}

registerOnChange(fn: Function) {
  // your code here
}
registerOnTouched(fn: Function) {
  // your code here
}

并在父组件模板中

<custom-element formControlName="fieldname"></custom-element>

更多详细信息(以及更深入的解释),您可以查看https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html