问题
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
Directive:
@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');
}
}
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.
回答1:
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
});
}
}
来源:https://stackoverflow.com/questions/55255686/angular-listen-for-enable-disable-elements