【问题标题】:Angular listen for enable/disable elements角度监听启用/禁用元素
【发布时间】:2019-08-10 20:20:06
【问题描述】:

我正在尝试找出某个元素是否在 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,因为我正在开发的指令不需要启用和禁用按钮,它只监听禁用属性的变化。

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

【问题讨论】:

  • @HostListener 正在监听 事件,没有 disabled 事件。请澄清你的问题。如果你真的需要监听 DOM 变化,你可能不得不使用 MutationObserver developer.mozilla.org/en-US/docs/Web/API/MutationObserver
  • @Dimanoid 我想监听禁用的属性变化
  • 好吧,那么我认为MutationObserver 是你唯一的选择。
  • @Dimanoid 如果你能发布答案我会接受它,你能帮我突变观察者吗

标签: angular angular2-directives


【解决方案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
    });
  }

}

【讨论】:

  • 你认为扫描整个 Dom 的功能是不是有点矫枉过正
  • 据我所知,它只会监听宿主元素的属性变化。所以我认为它并不太贵。
  • 在observe() 中使用attributeFilter: ['disabled'] 观察禁用属性是个好主意
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
  • 2019-06-08
  • 2018-07-10
相关资源
最近更新 更多