角听启用/禁用元素 [英] Angular listen for enable/disable elements

查看:107
本文介绍了角听启用/禁用元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定Angular指令中是否禁用了元素.

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

指令:

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

但是我不想使用setter,因为我正在开发的指令不需要启用和禁用按钮,它仅侦听禁用属性的更改.

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.

推荐答案

不确定这是否正确,但是可以.

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

}

这篇关于角听启用/禁用元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆