From 598a02eb7dd84e8271c4e2c850cbf20a5aa848f0 Mon Sep 17 00:00:00 2001 From: Oleksandr Perepichai Date: Thu, 15 May 2025 09:59:03 +0300 Subject: [PATCH] feat: 3 directive enhancement --- .../src/app/app.component.ts | 12 +++--- .../src/app/empty.directive.ts | 41 +++++++++++++++++++ 2 files changed, 46 insertions(+), 7 deletions(-) create mode 100644 apps/angular/3-directive-enhancement/src/app/empty.directive.ts diff --git a/apps/angular/3-directive-enhancement/src/app/app.component.ts b/apps/angular/3-directive-enhancement/src/app/app.component.ts index 8d37369a1..cd952d310 100644 --- a/apps/angular/3-directive-enhancement/src/app/app.component.ts +++ b/apps/angular/3-directive-enhancement/src/app/app.component.ts @@ -1,19 +1,17 @@ -import { NgFor, NgIf } from '@angular/common'; import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { NgForEmpty } from './empty.directive'; interface Person { name: string; } @Component({ - imports: [NgFor, NgIf], + imports: [NgForEmpty], selector: 'app-root', template: ` - -
- {{ person.name }} -
-
+
+ {{ person.name }} +
The list is empty !! `, styles: [], diff --git a/apps/angular/3-directive-enhancement/src/app/empty.directive.ts b/apps/angular/3-directive-enhancement/src/app/empty.directive.ts new file mode 100644 index 000000000..085b2c86d --- /dev/null +++ b/apps/angular/3-directive-enhancement/src/app/empty.directive.ts @@ -0,0 +1,41 @@ +import { NgFor } from '@angular/common'; +import { + Directive, + EmbeddedViewRef, + inject, + Input, + OnChanges, + TemplateRef, + ViewContainerRef, +} from '@angular/core'; + +@Directive({ + // eslint-disable-next-line @angular-eslint/directive-selector + selector: '[ngForEmpty]', + standalone: true, + hostDirectives: [ + { + directive: NgFor, + inputs: ['ngForOf:ngForEmptyOf'], + }, + ], +}) +class NgForEmptyDirective implements OnChanges { + private vcr = inject(ViewContainerRef); + + @Input() ngForEmptyOf: T[] | undefined; + + @Input() ngForEmptyElse!: TemplateRef; + + private ref?: EmbeddedViewRef; + + ngOnChanges(): void { + this.ref?.destroy(); + + if (!this.ngForEmptyOf || this.ngForEmptyOf.length === 0) { + this.ref = this.vcr.createEmbeddedView(this.ngForEmptyElse); + } + } +} + +export { NgForEmptyDirective as NgForEmpty };