Skip to content

Commit 9b6442b

Browse files
committed
refactor(visible): signal inputs, cleanup
1 parent 7a306a9 commit 9b6442b

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed
Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,37 @@
1-
import { Directive, inject, Input, TemplateRef, ViewContainerRef } from '@angular/core';
1+
import { Directive, effect, inject, input, TemplateRef, ViewContainerRef } from '@angular/core';
22

33
@Directive({
4-
selector: '[cVisible]'
4+
selector: '[cVisible]',
5+
exportAs: 'cVisible'
56
})
7+
/**
8+
* A directive that conditionally includes a template based on the value of an input boolean.
9+
*
10+
* @example
11+
* ```html
12+
* <ng-template [cVisible]="isVisible">Content to display</ng-template>
13+
* ```
14+
*
15+
* @remarks
16+
* This directive uses Angular's dependency injection to get references to `TemplateRef` and `ViewContainerRef`.
17+
* It creates or clears the embedded view based on the value of the `cVisible` input.
18+
*/
619
export class VisibleDirective {
720
readonly #templateRef = inject<TemplateRef<any>>(TemplateRef);
821
readonly #viewContainer = inject(ViewContainerRef);
922

1023
#hasView!: boolean;
1124

12-
@Input() set cVisible(condition: boolean) {
25+
readonly cVisible = input<boolean>();
26+
27+
readonly #visibleEffect = effect(() => {
28+
const condition = this.cVisible();
1329
if (condition && !this.#hasView) {
1430
this.#viewContainer.createEmbeddedView(this.#templateRef);
1531
this.#hasView = true;
1632
} else if (!condition && this.#hasView) {
1733
this.#viewContainer.clear();
1834
this.#hasView = false;
1935
}
20-
}
36+
});
2137
}

0 commit comments

Comments
 (0)