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;
}
}




Sunday 20 November 2022

Angular functional guard to check on the user role to guard your routes

functional guard to check on the user role  to guard your routes. 


The functional guard accepts a param for the user role 


Less verbose than a class based guard



    use canMatch to skip a route dynamically in combination with functional guards. 

  👍 Super handy when a path should lead to different comp depending on some logic 

  👋 canLoad is going to be deprecated in favor of canMatch


    


Saturday 19 November 2022

Directive composition API in Angular 15

our directive stand alone by adding standalone property inside directive declaration 

import { Directive } from '@angular/core';

@Directive({
  selector: '[appRedColor]',
  host:{'style': 'color:red;'},
  standalone: true
})
export class RedColorDirective {

  constructor() { }

}

Now the text inside testdirective component will be displayed in red color.

<app-testdirective></app-testdirective>

And our code looks simple without adding an extra directive in component tag.

We can add more than one directive inside hostDirectives property.


@Component({
  selector: 'app-testdirective',
  templateUrl: './testdirective.component.html',
  styleUrls: ['./testdirective.component.scss'],
  hostDirectives:[RedColorDirective,HeightDirective,FontStyleDirective,......]
})
export class TestdirectiveComponent {
}

We can add hostDirectives inside an another directive as well.