【问题标题】:Select FormGroup with Angular Directive使用 Angular 指令选择 FormGroup
【发布时间】:2020-10-07 12:12:30
【问题描述】:

我知道可以为这样的自定义指令选择 Angular 反应式表单控件:

@Directive({
    selector: '[formControl], [formControlName]',
})
export class MyDirective {
    constructor(
        private controlDir: NgControl,
        private el: ElementRef
    ) {
        const control = controlDir.control;
    }
}

然而,这种方法在选择 [formGroup] 时不起作用,尽管它也是从 AbstractControl 派生的(抛出 NullInjectorError)。我也尝试注入 NgForm 而不是 NgControl 但没有成功。

有没有办法通过 Angular 指令访问 FormGroup?

Stackblitz Example

【问题讨论】:

  • 查看 formControl 指令的源代码github.com/angular/angular/blob/… 我看到他们使用 providers 元素来注入 ngControl 如果您想要实现的是扩展您可能需要的默认 formControl 指令以不同的方式命名并扩展原生的
  • 感谢您的评论。我想选择一个现有的 FormGroup 来访问它的控件
  • 在大多数情况下,在初始化 formGroup 的角度组件中,使用 new Formgroup(...) 您可以使用 formGroup.controls 引用来访问它的控件angular.io/api/forms/FormGroup
  • 我知道这一点,但我想使用 angular 指令动态查找 formGroups
  • 用这几个信息很难理解在这种情况下动态意味着什么,另一种查找所有 formGroup 指令的方法是使用angular.io/api/core/ViewChildren,如下所示@ViewChildren(FormGroup) viewChildren: QueryList;

标签: angular


【解决方案1】:

找到另一个question

能够获得对formGroup的控件的引用,如下所示

   export class MyFormGroupDirective implements OnInit {
       constructor(...,private formGroup: FormGroupDirective) { 
           console.log(Object.keys(this.formGroup.form.controls))
       }
   ...}

在自定义 MyFormGroupDirective 中注入 formGroupDirective

Here's the stackblitz fork with the above solution

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    相关资源
    最近更新 更多