I am working on integrating an Angular directive with a signal that receives values from a store selector. This signal is crucial for determining whether a button should be disabled or not. I'm curious about the best approach to listen to this signal - can I utilize the effect (or is it considered bad practice?) or is there a better alternative?
Within my directive, the effect resides in the constructor, and I previously attempted using ngOnChanges
(an outdated piece of code that I modified as I shifted to using signals). The MaintenanceDisableErp
signal originates from a selector.
I learned from the documentation that signals are designed for "Adding custom DOM behavior that can't be expressed with template syntax". Is this the intended purpose of signals in this scenario?
import {
Directive,
Input,
HostListener,
Renderer2,
ElementRef,
inject,
effect,
} from "@angular/core";
import { MatSnackBar } from "@angular/material/snack-bar";
import { NotificationService } from "@core/services/notification.service";
import { Store } from "@ngrx/store";
import { toSignal } from "@angular/core/rxjs-interop";
import { selectDisabledErp } from "@core/_state/core.reducer";
@Directive({
selector: "[appErpDisabled]",
})
export class DisableNotifyDirective {
store = inject(Store);
maintenanceDisableErp = toSignal(this.store.select(selectDisabledErp));
constructor(private el: ElementRef, private renderer: Renderer2) {
effect(() => {
this.renderer.setAttribute(
this.el.nativeElement,
"disabled",
this.maintenanceDisableErp() ? "true" : "false"
);
});
}
}