从 Angular 中的自定义表单组件访问 FormControl [英] Get access to FormControl from the custom form component in Angular

查看:48
本文介绍了从 Angular 中的自定义表单组件访问 FormControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

However, I want to access the FormControl instance, associated with my component. I'm using reactive forms with FormBuilder and providing form control using formControlName attribute.

SO,如何从我的自定义表单组件内部访问 FormControl 实例?

SO, how do I access FormControl instance from inside of my custom form component?

推荐答案

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

This solution was born from the discussion in the Angular repository. Please, make sure to read it or even better to participate if you are interested in this problem.

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

I've studied the code of FormControlName directive and it's inspired me to write the following solution:

@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 注入组件,然后使用通过 formControlName 绑定获得的控件名称从中获取特定的 FormControl.

I'm injecting the parent FormGroup to the component and then getting the specific FormControl from it using control name obtained through formControlName binding.

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

However, be advised, that this solution is tailored specifically for the use case where FormControlName directive is used on host element. It won't work in other cases. For this you will need to add some additional logic. If you think, that this should be addressed by Angular, make sure to visit the discussion.

这篇关于从 Angular 中的自定义表单组件访问 FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆