如何在角度指令中绑定如何检测宿主元素的值

时间:2019-04-19 11:52:42

标签: angular directive

如果使用自定义指令输入了一些文本,我正在尝试向输入字段添加属性。我可以在@HostListener('change')事件中做到这一点。 这对于创建页面来说是完全可以的,但是在编辑页面中,数据是通过NgModel异步加载并绑定的,因此我找不到任何这样做的事件。任何帮助,将不胜感激。

@Directive({
  selector: '[testDirective]'
})
export class TestDirective implements AfterViewInit{

    constructor(private el: ElementRef) { }

    @HostListener('change') onChange() {
        this.setCustomAttribute();
    }

    @HostListener('input') inputEvent() {
        console.log("i am in input event");
        //input event is not working either
    }

    private setCustomAttribute(){
        if(this.el.nativeElement.value==null||this.el.nativeElement.value==""){
            this.el.nativeElement.setAttribute("custom-attribute", "false");
        }else{
            this.el.nativeElement.setAttribute("custom-attribute", "true")
        } 
    }
}


<input testDirective name="somefield" required  type="text" [(ngModel)]="object.somefield">

2 个答案:

答案 0 :(得分:0)

您可以在指令内注入“ NgControl”,然后像这样附加到valueChanges上

@Directive({
  selector: '[testDirective]'
})
export class TestDirective implements AfterViewInit{



      constructor(private el: ElementRef,private ngControl:NgControl) { 
          this.listenToChanges();
          }




    private listenToChanges(){
               this.ngControl.valueChanges.subscribe(()=>{
                this.setCustomAttribute(); })
           }


    @HostListener('change') onChange() {
        this.setCustomAttribute();
    }

    @HostListener('input') inputEvent() {
        console.log("i am in input event");
        //input event is not working either
    }

    private setCustomAttribute(){
        if(this.el.nativeElement.value==null||this.el.nativeElement.value==""){
            this.el.nativeElement.setAttribute("custom-attribute", "false");
        }else{
            this.el.nativeElement.setAttribute("custom-attribute", "true")
        } 
    }
}


<input testDirective name="somefield" required  type="text" [(ngModel)]="object.somefield">

它将自动退订,而指令将被销毁

答案 1 :(得分:0)

尝试ngAfterViewInit方法

function up()