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

How to detect the value of a host element is binded using in an 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">

您可以在指令中注入 "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">

会自动退订,同时指令会被销毁

试试 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")
    } 
}