Thursday 24 November 2022

angular v15 directive ngFor handling empty list

 


// hello.component.ts


import { Component, Input } from '@angular/core';
import { NgForEmpty } from './ng-of-empty';

@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>
<ul>
<li *ngFor="let p of persons; empty: emptyTmpl">{{p}}</li>
</ul>
<ng-template #emptyTmpl>Empty list</ng-template>
`,
styles: [`h1 { font-family: Lato; }`],
standalone: true,
imports: [NgForEmpty],
})
export class HelloComponent {
@Input() name: string;
persons = ['Dignāga','Dharmakīrti','Kamalaśīla','Śāntarakṣita',
             'Asanga','Vasubandhu'];
}


// ng-of-empty.ts



import { NgFor, NgIf } from '@angular/common';
import { Directive, inject, Input } from '@angular/core';

@Directive({
selector: '[ngFor]',
standalone: true,
hostDirectives: [
{ directive: NgFor, inputs: ['ngForOf'] },
{ directive: NgIf, inputs: ['ngIfElse: ngForEmpty'] },
],
})
export class NgForEmpty<T> {
private readonly ngIf = inject(NgIf, { host: true });

@Input() set ngForOf(ngFor: T[] | undefined) {
this.ngIf.ngIf = ngFor && ngFor.length > 0;
}
}




No comments:

Post a Comment