我试图找出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,因为我正在开发的指令不需要启用和禁用按钮,它只会监听禁用属性更改。
我希望它是禁用逻辑的通用。
不确定这是否是正确的方法,但它的工作原理。
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
});
}
}