javascript – Angular:ControlValueAccessor更新到共享相同formControlName的所有组件

我希望这张图片能说明我想做什么.

《javascript – Angular:ControlValueAccessor更新到共享相同formControlName的所有组件》

所以我想做一个共享相同formControlName的自定义无线电组件.
单击无线电时,共享相同formControlName的其余组件应使用活动值更新.

我该怎么做?

最佳答案 我已经在几个输入之间仅共享formControlName来测试行为,并且它不会仅基于此绑定属性进行更新.它看起来像是变通方法,ngModel(仅限v5或更早版本),或者需要一个函数来完成所需的行为.这里有一个封闭的问题和一些详细的对话框:

https://github.com/angular/angular/issues/10036

最为显着地:

Shared form controls are only supported right now for naturally grouped controls like radio buttons (which have a shared registry). For text inputs sharing controls, ngModel is the only option if you’d like them to be synced. We’re not likely to add this functionality to reactive forms given the workaround, so closing. If you feel there is a use case for this that cannot be solved any other way, please feel free to open an issue with some more info about your use case.

但是有一些关于变通方法的评论.

解决方法

最吸引人的是:

a custom directive to force [FormControl] and [FormControlName] to update when the FormControl updates.

https://gist.github.com/Dyljyn/59e95fbe09a24b1835667a1a5e401e5a

功能

您可以在组件中创建一个函数来设置formControl的值:

setControl(value){
    this.form.controlName = value
}

并执行一个调用该函数的on click事件:

<input type="radio" formControlName="controlName" (click)="setControl(x)">
点赞