Sachith Rukshan
Sachith Rukshan

Reputation: 351

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

Upvotes: 1

Views: 672

Answers (1)

John Velasquez
John Velasquez

Reputation: 3451

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

Upvotes: 2

Related Questions