Как определить значение элемента хоста с помощью угловой директивы - PullRequest
0 голосов
/ 19 апреля 2019

Я пытаюсь добавить атрибут в поле ввода, если какой-либо текст вводится с использованием пользовательской директивы.Я могу сделать это в случае события @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 голосов
/ 19 апреля 2019

попробуйте метод 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")
    } 
}
0 голосов
/ 19 апреля 2019

вы можете внедрить "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">

и он автоматически отписывается, а директива будет уничтожена

...