Browse Source

Refactor AbpVisibleDirective to use signal inputs

Replaces @Input with Angular's new signal-based input and effect for reactive updates. Simplifies lifecycle management by removing OnInit and handling input changes via effect, improving code clarity and reactivity.
pull/24777/head
Fahri Gedik 8 months ago
parent
commit
7686d1b2ab
  1. 32
      npm/ng-packs/packages/theme-shared/src/lib/directives/visible.directive.ts

32
npm/ng-packs/packages/theme-shared/src/lib/directives/visible.directive.ts

@ -1,37 +1,41 @@
import { OnInit, Directive, OnDestroy, Input, ViewContainerRef, TemplateRef, inject } from '@angular/core';
import { Directive, OnDestroy, ViewContainerRef, TemplateRef, inject, input, effect } from '@angular/core';
import { EMPTY, from, Observable, of, Subscription } from 'rxjs';
type VisibleInput = boolean | Promise<boolean> | Observable<boolean> | undefined | null;
@Directive({
selector: '[abpVisible]',
})
export class AbpVisibleDirective implements OnDestroy, OnInit {
export class AbpVisibleDirective implements OnDestroy {
private viewContainerRef = inject(ViewContainerRef);
private templateRef = inject<TemplateRef<unknown>>(TemplateRef);
conditionSubscription: Subscription | undefined;
isVisible: boolean | undefined;
private conditionSubscription: Subscription | undefined;
private isVisible: boolean | undefined;
private condition$: Observable<boolean> = of(false);
@Input() set abpVisible(
value: boolean | Promise<boolean> | Observable<boolean> | undefined | null,
) {
this.condition$ = checkType(value);
this.subscribeToCondition();
}
readonly abpVisible = input<VisibleInput>();
private condition$: Observable<boolean> = of(false);
ngOnInit(): void {
this.updateVisibility();
constructor() {
effect(() => {
const value = this.abpVisible();
this.condition$ = checkType(value);
this.subscribeToCondition();
});
}
ngOnDestroy(): void {
this.conditionSubscription?.unsubscribe();
}
private subscribeToCondition() {
this.conditionSubscription?.unsubscribe();
this.conditionSubscription = this.condition$.subscribe(value => {
this.isVisible = value;
this.updateVisibility();
});
}
private updateVisibility() {
this.viewContainerRef.clear();
// it should be false not falsy
@ -42,7 +46,7 @@ export class AbpVisibleDirective implements OnDestroy, OnInit {
}
}
function checkType(value: boolean | Promise<boolean> | Observable<boolean> | undefined | null) {
function checkType(value: VisibleInput) {
if (value instanceof Promise) {
return from(value);
} else if (value instanceof Observable) {

Loading…
Cancel
Save