HostBinding a FormControl to a input within a Directive

609 Views Asked by At

I am having trouble adding a formControl to a input via a HostBinding inside a directive attached to the Input. Please let me know if this is a possible approach and if so how to do it.

Input

<input matInput searchInput>

The Directive (searchInput)

@Directive({
    selector: '[searchInput]',
})
export class SearchableSelectDirective implements AfterViewInit {
    @HostBinding('attr.[formControl]') control: FormControl = new FormControl('');

    ngAfterViewInit(): void {
        this.sub = this.control.valueChanges.subscribe((value: string) => {
            console.log(value);
        });
    }
}
1

There are 1 best solutions below

3
John Velasquez On BEST ANSWER

To access the FormControl reference you need to use NgControl

@Directive({
    selector: '[searchInput]',
})
export class SearchableSelectDirective implements AfterViewInit {
    sub: any;
    constructor(private ngControl: NgControl) {}

    ngAfterViewInit(): void {
        this.sub = this.ngControl.valueChanges.subscribe((value: string) => {
            console.log(value);
        });
    }
}