angularangular-directiveangular2-hostbinding

HostBinding a FormControl to a input within a Directive


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

Solution

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