Angular 监听 enable/disable 个元素

Angular listen for enable/disable elements

我正在尝试查明某个元素是否在 Angular 指令中被禁用。

到目前为止,我正在尝试使用主机听众,但没有成功

指令:

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

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

它对我有用 setter

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

但我不想使用 setter 因为我正在开发的指令不需要启用和禁用按钮,它只监听禁用属性的变化。

我希望它是通用的禁用逻辑。

不确定这是否正确,但确实有效。

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
    });
  }

}