69

我的 Angular 应用程序中有一个自定义表单控件组件,它实现了ControlValueAccessor接口。

但是,我想访问FormControl与我的组件关联的实例。我正在使用响应式表单并使用属性FormBuilder提供表单控制。formControlName

那么,如何FormControl从自定义表单组件内部访问实例?

4

5 回答 5

60

这个解决方案诞生于 Angular 存储库中的讨论。如果您对此问题感兴趣,请务必阅读或更好地参与。


我研究了FormControlName指令的代码,它启发了我编写以下解决方案:

@Component({
  selector: 'my-custom-form-component',
  templateUrl: './custom-form-component.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: CustomFormComponent,
    multi: true
  }]
})
export class CustomFormComponent implements ControlValueAccessor, OnInit {

  @Input() formControlName: string;

  private control: AbstractControl;


  constructor (
    @Optional() @Host() @SkipSelf()
    private controlContainer: ControlContainer
  ) {
  }


  ngOnInit () {

    if (this.controlContainer) {
      if (this.formControlName) {
        this.control = this.controlContainer.control.get(this.formControlName);
      } else {
        console.warn('Missing FormControlName directive from host element of the component');
      }
    } else {
      console.warn('Can\'t find parent FormGroup directive');
    }

  }

}

我将父FormGroup组件注入组件,然后使用通过绑定FormControl获得的控件名称从中获取特定组件。formControlName

但是,请注意,此解决方案是专门为FormControlName在主机元素上使用指令的用例量身定制的。它在其他情况下不起作用。为此,您需要添加一些额外的逻辑。如果您认为这应该由 Angular 解决,请务必访问讨论

于 2017-06-24T03:46:16.320 回答
53

通过指令formControlName绑定时,用作输入参数不起作用。[formControl]

这是一个无需任何输入参数即可双向工作的解决方案。

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

于 2018-07-01T20:56:18.633 回答
13

基于之前在评论中找到的答案和文档,我认为这是ControlValueAccessor基于组件的最干净的解决方案。

// No FormControl is passed as input to MyComponent
<my-component formControlName="myField"></my-component>
export class MyComponent implements AfterViewInit, ControlValueAccessor  {

  constructor(@Optional() @Self() public ngControl: NgControl) {
    if (ngControl != null) {
      // Setting the value accessor directly (instead of using
      // the providers) to avoid running into a circular import.
      ngControl.valueAccessor = this;
    }
  }

    ngAfterContentInit(): void {
       const control = this.ngControl && this.ngControl.control;
       if (control) {
          // FormControl should be available here
       }
    }
}
于 2020-05-17T18:52:20.063 回答
4

正如@Ritesh 已经在评论中所写,您可以将表单控件作为输入绑定传递:

<my-custom-form-component [control]="myForm.get('myField')" formControlName="myField">
</my-custom-form-component>

然后您可以在自定义表单组件中获取表单控件实例,如下所示:

@Input() control: FormControl;
于 2018-01-25T14:51:36.603 回答
3

这是适用于 FormControlName 和 FormControl 输入的已接受答案的简化/清理版本:

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) { }
}
于 2020-10-23T04:46:44.380 回答