【问题标题】:How to get FormControl instance from ControlValueAccessor如何从 ControlValueAccessor 获取 FormControl 实例
【发布时间】:2018-01-27 02:23:14
【问题描述】:

我有以下组件:

@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 {
    ...
}

我可以通过这些输入分配和更改值:

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

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

通过创建 @Input() formControl 并不能解决问题。因为它没有涵盖通过 formControlName 分配表单控件的情况。

【问题讨论】:

    标签: angular controls directive accessor


    【解决方案1】:

    来自我对此stackblitz question的回答

    另一种解决方案是添加为提供程序 NG_VALIDATORS。因此,在我们的函数 validate 中,我们可以将控件存储在一个变量中

    public validate(c: FormControl) {
      if (!this.control)
        this.control=c;
      return null;
    

    见stackblitz

    【讨论】:

      【解决方案2】:

      看起来 injector.get(NgControl) 正在发出弃用警告,所以我想加入另一个解决方案:

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

      诀窍是还从提供程序数组中删除 NG_VALUE_ACCESSOR,否则您会得到循环依赖。

      更多信息请见this talk by Kara Erickson of the Angular team。

      【讨论】:

      • 这应该是 2019 年 Angular 7 公认的解决方案。
      • 你能显示什么是弃用警告吗?
      • FWIW,她的演讲完全值得你花时间。但是,如果您正在寻找特定的 NgControl 位,它从 19:07 开始。
      • 添加到这个答案:不需要从提供者中删除 NG_VALUE_ACCESSOR,或者添加 ngControl.valueAccessor = this;您可以像这样将 NG_VALUE_ACCESSOR 添加到提供程序:``` lang-js { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyComponent), multi: true, }, ``` 然后你可以在构造函数中注入 NgControl
      • 谢谢@EricLiprandi,这非常有用。
      【解决方案3】:

      一种可能的解决方案是通过Injector 获取NgControl 实例:

      import { NgControl } from '@angular/forms';
      export class PasswordComponent implements ControlValueAccessor {
        ...
        ngControl: NgControl;
      
        constructor(private inj: Injector) {
          ...
        }
      
        ngOnInit() {
          this.ngControl = this.inj.get(NgControl)
        }
      

      然后你可以得到像这样的状态

      ngControl.control.status
      

      另见

      【讨论】:

        猜你喜欢
        • 2021-01-25
        • 2021-12-10
        • 1970-01-01
        • 2017-04-02
        • 2010-10-12
        • 2019-07-08
        • 1970-01-01
        • 2018-11-11
        • 1970-01-01
        相关资源
        最近更新 更多