How to get FormControl instance from ControlValueAccessor

前端 未结 3 663
温柔的废话
温柔的废话 2020-12-29 05:35

I\'ve the following component:

@Component({
    selector: \'pc-radio-button\',
    templateUrl: \'./radio-button.component.html\',
    providers: [
        {         


        
相关标签:
3条回答
  • 2020-12-29 06:17

    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
    0 讨论(0)
  • 2020-12-29 06:18

    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.

    0 讨论(0)
  • 2020-12-29 06:18

    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

    0 讨论(0)
提交回复
热议问题