Angular:从指令访问 FormControl

Pax*_*rce 10 typescript angular-directive angular

我想通过自定义指令将验证器动态添加到我的 FormControl。

@Directive({
    selector: "[idNumber]",
})
export class IdNumberDirective implements OnInit {

    constructor(private formControl: FormControl) { }

    ngOnInit() {
        this.addValidators(this.formControl);
    }

    addValidators(formControl: FormControl) {
        formControl.setValidators(Validators.compose(
            [Validators.required,
            Validators.minLength(3),
            Validators.maxLength(8)
            ]
        ));
    }



<mat-form-field>
    <mat-label>{{label}}</mat-label>
    <input matInput
        [formControl]="idNumberFormControl"
        [placeholder]="placeholder"
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)


我不需要引用 nativeElement(通过 ElementRef)。
我想引用 formControl ...
... 并使用它:

// HTML with my custom directive 'idNumber' ////////
<custom-input-string
    idNumber 
    [name]="'idNumber'"
    [label]="Id Number"
    [placeholder]="">
</custom-input-string>

// TS ////////
@ViewChild(CustomInputStringComponent) child: CustomInputStringComponent;

ngAfterViewInit() {
    setTimeout(() => {
        this.child.insertIntoForm(this.signupForm);
    }, 0);
}
Run Code Online (Sandbox Code Playgroud)


有任何想法吗?
谢谢你们。

小智 11

这是使用指令将验证器附加到表单控件的示例。

闪电战

请注意,使用它会导致丢失所有以前的验证器。

constructor(
  // Get the control directive
  private control: NgControl
) { }
ngOnInit() {
  const abstractControl = this.control.control;
  abstractControl && abstractControl.setValidators([Validators.required]);
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案很好,但我认为主要方面(使用“NgControl”而不是OP的“FormControl”)太有价值了,不能留在外部链接(Stackblitz)中。我建议我们将这部分直接放在答案中,就像 @Suresh 在他的答案中所做的那样。 (3认同)

Sur*_*iya 7

如果您使用 NgControl 和构造函数 DI 注入,我们可以有一个指令适用于 formControlName 或模板驱动表单中来自反应式表单的表单控件:

指示:

import { Directive } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[my-directive]'
})
export class MyDirective {
  constructor(private el: ElementRef, private control : NgControl) { }

}
Run Code Online (Sandbox Code Playgroud)

  • 你能用更多的代码更新你的答案吗?另外 - 您建议中的“私人 el:ElementRef”有什么意义? (2认同)