Angular team introduced a new feature called “Directive composition API” in Angular 15 Version.
Let’s understand what is this directive composition in Angular.
We will create simple directive in Angular which apply the CSS color to an Angular component.
ng generate directive redColor
And in the directive definition we add the below code:
import { Directive } from '@angular/core';
@Directive({
selector: '[appRedcolor]',
host: { style: 'color:red' },
})
export class RedcolorDirective {
constructor() {}
}
Now apply the directive to a component in Angular.
ng generate component testdirective
And in the component HTML add the redColor
directive.
<app-testdirective appRedColor></app-testdirective>
//Inside testdirective.component.html
<p> Hello I am displayed in red color using directive</p>
Now the text inside testdirective
component will be displayed in red
color.
Now using Directive composition API we can directly add the directive inside component declaration using
hostDirectives
property.
import { Component } from '@angular/core';
import { RedColorDirective } from '../red-color.directive';
@Component({
selector: 'app-testdirective',
templateUrl: './testdirective.component.html',
styleUrls: ['./testdirective.component.scss'],
hostDirectives:[RedColorDirective]
})
export class TestdirectiveComponent {
}
No need anymore to add appRedColor
directive to the component.
<app-testdirective></app-testdirective>
But here is the catch, you will get an error saying Host directive must me standalone
error NG2014: Host directive RedColorDirective must be standalone
hostDirectives:[RedColorDirective]
That means we can add only standalone directives in hostDirectives
array.
Let’s make our directive stand alone by adding standalone
property inside directive declaration and remove the definition from the app.module.ts
file.
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, and our code looks simple without adding an extra directive in component tag.
<app-testdirective></app-testdirective>
PS: We can add more than one directive inside hostDirectives
property.
@Component({
selector: 'app-testdirective',
templateUrl: './testdirective.component.html',
styleUrls: ['./testdirective.component.scss'],
hostDirectives:[RedColorDirective,AnotherDirective,......]
})
export class TestdirectiveComponent {
}
PS 2 : we can create standalone directives with the following command Line :
ng generate directive directiveName --standalone=true