Angular侦听启用/禁用元素

问题描述 投票:1回答:1

我试图找出Angular指令中是否禁用了一个元素。

到目前为止,我正在尝试与主持人听众没有运气

指示:

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

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

这对我来说很有用

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

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

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

angular angular2-directives
1个回答
1
投票

不确定这是否是正确的方法,但它的工作原理。

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

}
© www.soinside.com 2019 - 2024. All rights reserved.