Angular 15 : Unlocking the Power of Directive Composition

Abhishek Wadalkar
1 min readSep 8, 2024

--

Angular version 15 introduced a game-changing feature called directive composition. This powerful concept allows you to compose multiple directives on components and directives, enabling you to declare directives in class decorators instead of HTML templates.

What is Directive Composition?

Directive composition lets you automatically apply directives to components, similar to directive selectors. It also enables you to create directives that apply multiple directives using a single selector.

Example: Automatically Applying Directives

Suppose you have a ButtonComponent and want to automatically apply TypeDirective and SizeDirective to it. You can use directive composition to achieve this:

@Component({
...
hostDirectives: [
{ directive: TypeDirective, inputs: ['appType'] },
{ directive: SizeDirective, inputs: ['appSizeType'] }
]
})
export class ButtonComponent {}

Aliasing Input Values

You can also alias input values of the directive:

{ directive: TypeDirective, inputs: ['btLibsUiType: style'] }

Then, in your HTML template:

<app-button [style]="'secondary'">Submit</app-button>

Using Directive Composition Inside Directives

Directive composition works the same way inside directives. You can declare textColorDirective inside the hostDirectives array of backgroundColorDirective.

Important Notes

  • Use standalone directives when using directive composition.
  • Be cautious when using directive composition, as it can impact memory usage and performance.

Conclusion:

Directive composition is a powerful feature in Angular that can enhance your applications. By mastering this concept, you can create more efficient and reusable directives. Stay tuned for the next section, where we’ll explore Angular pipes!

--

--

Abhishek Wadalkar
Abhishek Wadalkar

Written by Abhishek Wadalkar

Passionate Frontend developer with 4 years experience, crafting seamless, user-centric web experiences. Exploring the world of web development and constantly.

No responses yet