How to get FormControl instance from ControlValueAccessor

不打扰是莪最后的温柔 提交于 2019-11-29 02:42:54

问题


I've the following component:

@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>

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

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


回答1:


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;
}

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

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




回答2:


One possible solution is to get NgControl instance via Injector:

import { NgControl } from '@angular/forms';
export class PasswordComponent implements ControlValueAccessor {
  ...
  ngControl: NgControl;

  constructor(private inj: Injector) {
    ...
  }

  ngOnInit() {
    this.ngControl = this.inj.get(NgControl)
  }

then you can get status like

ngControl.control.status

See also

  • Access valid value of custom form control



回答3:


Goes from my answer of this stackblitz question

Another solution is add as provider NG_VALIDATORS. So, in our function validate we can store the control in a variable

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

See stackblitz



来源:https://stackoverflow.com/questions/45755958/how-to-get-formcontrol-instance-from-controlvalueaccessor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!