Get access to FormControl from the custom form component in Angular

前端 未结 5 1056
野的像风
野的像风 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 01:03

    Here is a simplified/cleaned up version of the accepted answer that works for both FormControlName and FormControl inputs:

    export class CustomFormComponent implements ControlValueAccessor, OnInit {
    
      @Input() formControl: FormControl;
    
      @Input() formControlName: string;
    
      // get ahold of FormControl instance no matter formControl or formControlName is given.
      // If formControlName is given, then controlContainer.control is the parent FormGroup/FormArray instance.
      get control() {
        return this.formControl || this.controlContainer.control.get(this.formControlName);
      }
    
      constructor(private controlContainer: ControlContainer) { }
    }
    

提交回复
热议问题