如何检测主机元素的值是使用angular指令绑定的

问题描述 投票:0回答:2

如果使用自定义指令输入某些文本,我试图将属性添加到输入字段。我可以在@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">
angular directive
2个回答
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">

它将自动取消订阅,而指令将被销毁


0
投票

尝试ngAfterViewInit方法

  ngAfterViewInit(): void {
   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")
    } 
}
© www.soinside.com 2019 - 2024. All rights reserved.