Overview
What is the appClass
Directive?
The appClass
directive is a custom directive that we will create in Angular. Its purpose is to dynamically apply CSS classes to HTML elements based on certain conditions or use interactions. This directive will provide a flexible way to conditionally style elements without having to write complex logic in your templates.
Creating the appClass Directive
To create the appClass
directive, follow these steps:
Step 1: Generate the Directive
In your terminal, navigate to your Angular project's root folder and use the Angular CLI to generate a new directive.
ng generate directive appClass
This command will create the appClass
directive files in your project.
Step 2: Define the Directive Logic
Edit the app-class.directive.ts
file created by the CLI. The directive class should look like this:
import { Directive, Input, HostBinding } from '@angular/core';
@Directive({
selector: '[appClass]'
})
export class AppClassDirective {
@Input('appClass') set cssClasses(classObj: any) {
for (let key in classObj) {
if (classObj[key]) {
this.addClass(key);
} else {
this.removeClass(key);
}
}
}
constructor() {}
@HostBinding('class') currentClasses = '';
addClass(className: string) {
this.currentClasses = `${this.currentClasses} ${className}`;
}
removeClass(className: string) {
this.currentClasses = this.currentClasses.replace(className, '');
}
}
In this code, we have defined the AppClassDirective
. It takes an input named appClass
, which is an object with keys representing CSS class names and values indicating whether to apply the class.
The cssClasses
setter iterates through the keys of the input object and conditionally adds or removes classes based on the values. The @HostBinding('class')
decorator binds the currentClasses
property to the class
attribute of the host element, dynamically updating the element's classes as needed.
Step 3: Use the appClass Directive
Now you can use the appClass
directive in your templates to apply conditional CSS classes to HTML elements. Here's an example of how to use it:
any-component.html
<div [appClass]="{ 'red-text': isRedText, 'bold-text': isBoldText }">
This is a dynamically styled element.
</div>
any-component.ts
// declare these in host component
isRedText:boolean = false;
isBoldText:boolean = true;
any-component.css
.red-text{
color: red;
}
.bold-text{
font-size: xx-large;
font-weight: bold;
}
In this example, the appClass
directive is used to conditionally apply the red-text
and bold-text
CSS classes to the div
element based on the values of isRedText
and isBoldText
in your component.