Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: access FormControl from Directive

Tags:

People also ask

Can we add FormControl to div?

<div> is a readonly element, usually there's no point in binding form controls to it. You can also create your own custom components (or directives) that can be bound to form controls—if they implement ControlValueAccessor interface.


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.