Steps to implement Attribute Directive
Step 1: Create a new angular project
ng new [YOUR_PROJECT_NAME]
Folder Structure:
Dependencies:
"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:
<!--app.component.html-->
<div [ngStyle]="{ 'background-color': myfood === 'pizza' ? 'red' : 'blue' }">
hello GekksForGeeks
</div>
//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 :
For condition false:
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:
<!--app.component.html-->
<h1 [ngClass]="'one two'">Hello w3wiki</h1>
/* 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;
}
//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:
2. ngClass with Array
<!--app.component.html-->
<h1 [ngClass]="['two three']">Hello w3wiki</h1>
Output:
3. ngClass with object
In this type in boolean value when true then apply in element othewise false not effected
<!--app.comonent.html-->
<h1 [ngClass]="{'one':true ,'two':false}">Hello w3wiki</h1>
Output:
Angular 17 Attribute directive
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:
Table of Content
- What are attribute directives?
- Features of attribute Directives
- Types of attribute Directives