Get access to FormControl from the custom form component in Angular

前端 未结 5 1083
野的像风
野的像风 2020-11-29 00:09

I have a custom form control component in my Angular application, which implements ControlValueAccessor interface.

However, I want to access the F

5条回答
  •  猫巷女王i
    2020-11-29 00:53

    Using formControlName as an input parameter doesn't work when binding via the [formControl] directive.

    Here is a solution that works both ways without any input parameters.

    export class MyComponent implements AfterViewInit {
    
      private control: FormControl;
    
      constructor(
        private injector: Injector,
      ) { }
    
      // The form control is only set after initialization
      ngAfterViewInit(): void {
        const ngControl: NgControl = this.injector.get(NgControl, null);
        if (ngControl) {
          this.control = ngControl.control as FormControl;
        } else {
          // Component is missing form control binding
        }
      }
    }

提交回复
热议问题