【问题标题】:HostBinding a FormControl to a input within a Directive将 FormControl 绑定到指令中的输入
【发布时间】:2020-05-01 14:36:27
【问题描述】:

我在通过附加到输入的指令内的 HostBinding 将 formControl 添加到输入时遇到问题。 请让我知道这是否可行,如果可行,该怎么做。

输入

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

【问题讨论】:

    标签: angular angular-directive angular2-hostbinding


    【解决方案1】:

    要访问 FormControl 引用,您需要使用 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);
            });
        }
    }
    

    【讨论】:

    • 我需要从指令本身创建并附加 FormControl
    • 是的,您需要在输入元素中添加formControlformControlName
    • 我需要做的是通过指令而不是html来附加formcontrol
    猜你喜欢
    • 2017-04-20
    • 2019-09-26
    • 2021-04-26
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2018-06-30
    相关资源
    最近更新 更多