如何从ControlValueAccessor获取FormControl实例 [英] How to get FormControl instance from ControlValueAccessor

查看:144
本文介绍了如何从ControlValueAccessor获取FormControl实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下组件:

@Component({
    selector: 'pc-radio-button',
    templateUrl: './radio-button.component.html',
    providers: [
        {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => FieldRadioButtonComponent), multi: true}
    ]
})
export class RadioButtonComponent implements ControlValueAccessor {
    ...
}

我可以通过以下输入来分配和更改值:

I can assign and alter the value through these inputs:

<pc-radio-button [formControl]="formControl"></pc-radio-button>
<pc-radio-button [formControlName]="inputControlName"></pc-radio-button>

但是我需要该组件直接访问分配的formControl,因为我需要根据其状态添加样式.

However I need the component to have the direct access to the assigned formControl, as I need to add styles depending on its status.

通过创建 @Input()formControl 不能解决问题.由于它不涉及通过formControlName分配表单控件的情况.

By creating an @Input() formControl does not solve the problem. As it does not cover the case when form control is assigned via formControlName.

推荐答案

看起来好像jector.get(NgControl)抛出了弃用警告,所以我想使用其他解决方案:

It looks like injector.get(NgControl) is throwing a deprecation warning, so I wanted to chime in with another solution:

constructor(public ngControl: NgControl) {
  ngControl.valueAccessor = this;
}

诀窍是还要从providers数组中删除NG_VALUE_ACCESSOR,否则会得到循环依赖.

The trick is to also remove NG_VALUE_ACCESSOR from the providers array otherwise you get a circular dependency.

有关此问题的更多信息,请参见 Angular团队的Kara Erickson的演讲.

More information about this is in this talk by Kara Erickson of the Angular team.

这篇关于如何从ControlValueAccessor获取FormControl实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆