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

Angular: ControlValueAccessor update to all components who share same 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
}

并执行调用函数的点击事件:

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