Angular: access FormControl from Directive

PaxForce picture PaxForce · Sep 17, 2018 · Viewed 10.1k times · Source

I would like to add validators dynamically to my FormControl via a custom Directive.

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


I don't need to reference the nativeElement (via ElementRef).
I would like to reference the formControl...
...and use it as such:

// 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);
}


Any ideas?
Thank you all.

Answer

user4676340 picture user4676340 · Sep 17, 2018

Here is an example of using a directive to append validators to your form control.

Stackblitz

Note that using that will result in losing all of your previous validators.

ngOnInit() {
  const abstractControl = this.control.control;
  abstractControl && abstractControl.setValidators([Validators.required]);
}