Angular 17 Attribute directive
Last Updated :
02 May, 2024
In Angular, attribute directives are a powerful feature that allows you to manipulate the behavior and appearance of HTML elements. They are a fundamental building block for extending and customizing the behavior of components in Angular applications. In this article, we'll learn more about the concept of attribute directives in Angular, exploring their purpose and practical examples.
Prerequisites:
What are Attribute Directives?
Attribute directives are a type of directive in Angular that allows you to change the appearance or behavior of a DOM element by manipulating its attributes. Unlike structural directives like *ngIf
or *ngFor
, which alter the structure of the DOM, attribute directives modify the behavior or appearance of an element by applying transformations to its attributes.
The usual way to use attribute directives is to add them to HTML elements as attributes. With the @Directive decorator in Angular, attribute directives may be easily created. Using this decorator, you can specify which selector Angular should use to find the elements to which the directive should be applied. In particular, attribute directives work by monitoring modifications to the host element's attributes and implementing particular actions or features in response to those modifications.
Features of attribute Directives
- Dynamic Behavior Modification: Using attribute directives, you can change DOM element behavior dynamically in response to specific events.
- Enhanced Reusability: By encapsulating particular behaviors or functions that can be applied to several elements across your application, attribute directives help to increase code reusability.
- Access to DOM and Renderer: The ElementRef class gives attribute directives access to the DOM element they are applied to, enabling them to directly change the DOM if needed.
- Integration with Angular Forms: Custom validation, formatting, or transformation logic can be added to Angular forms using attribute directives, which improves their functionality. They can be used with form controls to change user input as necessary or to apply particular validation requirements.
- Integration with Dependency Injection: To inject services or other dependencies that they need, attribute directives can take advantage of Angular's dependency injection mechanism. This promotes better code organization and helps you develop directives that are more flexible and reusable.
- Directive Lifecycle Hooks: During the directive's lifetime, attribute directives can be used to carry out initialization, cleanup, and response to modifications. ngOnInit, ngOnChanges, ngAfterViewInit, ngAfterViewChecked, and other hooks are among them.
Types of attribute Directives
In Angular 17, there are essentially two built-in attribute directives.
- ngStyle
- ngClass
1. ngStyle:
The style properties of supplied dom components can be set using the ngstyle directives. The ngstyle directive can be used to set styles by assigning an object to it.
Steps to implement Attribute Directive
Step 1: Create a new angular project
ng new [YOUR_PROJECT_NAME]
Folder Structure:
angular17 file structureDependencies:
"dependencies": {
"@angular/animations": "^17.2.0",
"@angular/common": "^17.2.0",
"@angular/compiler": "^17.2.0",
"@angular/core": "^17.2.0",
"@angular/forms": "^17.2.0",
"@angular/platform-browser": "^17.2.0",
"@angular/platform-browser-dynamic": "^17.2.0",
"@angular/platform-server": "^17.2.0",
"@angular/router": "^17.2.0",
"@angular/ssr": "^17.2.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Example:
HTML
<!--app.component.html-->
<div [ngStyle]="{ 'background-color': myfood === 'pizza' ? 'red' : 'blue' }">
hello GekksForGeeks
</div>
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { NgStyle } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, NgStyle],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'geeks';
myfood = 'pizza';
}
In this code when condition will true then red otherwise blue.
Output:
For condition true :
.png)
For condition false:
.png)
2. ngClass:
By dynamically adding and removing CSS classes, it manages the appearance of elements.
Types of ngClass :
- ngClass with String
- ngClass with Array
- ngClass with Object
1. ngClass with String:
HTML
<!--app.component.html-->
<h1 [ngClass]="'one two'">Hello GeeksForGeeks</h1>
CSS
/* app.component.css */
h1 {
background-color: brown;
text-decoration: wavy;
}
.one {
background-color: brown;
color: black;
}
.two {
background-color: blueviolet;
color: azure;
font-size: large;
}
.three {
background-color: cadetblue;
}
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { NgClass } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, NgClass],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'geeks';
}
Output:
output 2. ngClass with Array
HTML
<!--app.component.html-->
<h1 [ngClass]="['two three']">Hello GeeksForGeeks</h1>
Output:.png)
3. ngClass with object
In this type in boolean value when true then apply in element othewise false not effected
HTML
<!--app.comonent.html-->
<h1 [ngClass]="{'one':true ,'two':false}">Hello GeeksForGeeks</h1>
Output:
.png)