Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Answer:3 #1146

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions apps/angular/3-directive-enhancement/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import { NgFor, NgIf } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { NgForDirective } from './ng-for.directive';

interface Person {
name: string;
}

@Component({
standalone: true,
imports: [NgFor, NgIf],
imports: [NgForDirective],
selector: 'app-root',
template: `
<ng-container *ngIf="persons.length > 0; else emptyList">
<div *ngFor="let person of persons">
{{ person.name }}
</div>
</ng-container>
<div *appNgFor="let person of persons; empty: emptyList">
{{ person.name }}
</div>
<ng-template #emptyList>The list is empty !!</ng-template>
`,
styles: [],
Expand Down
60 changes: 60 additions & 0 deletions apps/angular/3-directive-enhancement/src/app/ng-for.directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import {
Directive,
effect,
inject,
input,
TemplateRef,
ViewContainerRef,
} from '@angular/core';

interface NgForDirectiveContext<T> {
$implicit: T;
}

@Directive({
selector: '[appNgFor]',
standalone: true,
})
export class NgForDirective<T> {
private readonly viewContainer = inject(ViewContainerRef);
private readonly templateRef = inject(TemplateRef);

appNgForOf = input<T[]>();
appNgForEmpty = input<TemplateRef<unknown>>();

constructor() {
effect(() => {
const items = this.appNgForOf();
const empty = this.appNgForEmpty();
this.render(items, empty);
});
}

private render(items?: T[], empty?: TemplateRef<unknown>) {
if (items && items.length > 0) {
this.viewContainer.clear();
items.forEach((item) => {
this.viewContainer.createEmbeddedView(this.templateRef, {
$implicit: item,
});
});
} else {
this.viewContainer.clear();
if (empty) {
this.viewContainer.createEmbeddedView(empty);
}
}
}

/**
* The guard body is not used at runtime, and included only to avoid
* TypeScript errors.
* @See https://angular.dev/guide/directives/structural-directives#typing-the-directives-context
*/
static ngTemplateContextGuard<T>(
dir: NgForDirective<T>,
ctx: any,
): ctx is NgForDirectiveContext<T> {
return true;
}
}
Loading