【问题标题】:How to detect the value of a host element is binded using in an angular directive如何检测宿主元素的值是在角度指令中绑定使用的
【发布时间】:2019-04-19 11:52:42
【问题描述】:

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

【问题讨论】:

  • 试试ngOnInit()

标签: angular directive


【解决方案1】:

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

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

【讨论】:

  • 当数据绑定到 ngModel 时输入事件不起作用,我已经相应地更新了我的问题
  • 如果你有 ngModel,你可以将 NgControl 注入你的指令构造函数并订阅 valueChanges 事件
  • 感谢您的回复,您的解决方案有效。你能详细说明你的答案吗?我到底订阅了什么,当我更改页面时我应该取消订阅吗? @onik
【解决方案2】:

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

【讨论】:

  • 你好,我已经试过了,但是如果服务器很慢,也可以在 ngAfterViewInit 方法之后加载数据
猜你喜欢
  • 2018-11-19
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 2017-11-30
  • 2011-11-30
  • 2020-08-28
相关资源
最近更新 更多