简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM