gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:58:28 25 4
gpt4 key购买 nike

我希望这张图片能解释我想做什么。 enter image description here

所以我想做一个共享相同 formControlName 的自定义 radio 组件。单击单选按钮时,共享相同 formControlName 的其余组件应更新为事件值。

我该怎么做?

最佳答案

我测试了仅在多个输入之间共享 formControlName 的行为,并且它不会单独基于此绑定(bind)属性进行更新。看起来需要解决方法、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)">

关于javascript - Angular:ControlValueAccessor 更新所有共享相同 formControlName 的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51253504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com