Angular listen for enable/disable elements

和自甴很熟 提交于 2019-12-11 04:03:41

问题


I am trying to find out if an element is disabled in an Angular directive.

I am trying with host listeners so far no luck

Directive:

 @HostBinding('attr.disabled') isDisabled : boolean;

 @HostListener("disabled") disabled() {
     if(this.isDisabled) {
          // do some action 
     }
 }

It's working for me with the setter

@Input('disabled')
set disabled(val: string) {
  if(val) {
      this.elementRef.nativeElement.setAttribute('disabled', val);
  } else {
      this.elementRef.nativeElement.removeAttribute('disabled');
  }
}

but I don't want to use the setter because the directive I am developing does not need to enable and disable buttons, it only listens for disable attribute changes.

I want it to be generic of the disable logic.


回答1:


Not sure if this is the correct way but it works.

https://stackblitz.com/edit/mutationobserver-test

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appTestDir]'
})
export class TestDirDirective {
  observer: MutationObserver;

  constructor(private _el: ElementRef) {
    console.log(_el);
    this.observer = new MutationObserver(
      list => {
        for (const record of list) {
          console.log(record);
          if (record && record.attributeName == 'disabled' &&  record.target && record.target['disabled'] !== undefined) {
            this._el.nativeElement.style.border = record.target['disabled'] ? '2px dashed red' : null;
          }
        }
      }
    );
    this.observer.observe(this._el.nativeElement, {
      attributes: true,
      childList: false,
      subtree: false
    });
  }

}


来源:https://stackoverflow.com/questions/55255686/angular-listen-for-enable-disable-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!