Attribute Directives
Attribute directives are used to change the appearance or behavior of a DOM element by applying custom attributes. These directives are applied to elements as attributes and are denoted by square brackets. Attribute directives are often used for tasks such as dynamic styling, input validation, or DOM manipulation.
Built-in Attribute Directives:
1. ngClass: The NgClass directive allows us to conditionally apply CSS classes to HTML elements.
Syntax:
<div [ngClass]="{'class-name': condition}">
<!-- Content here -->
</div>
2. ngStyle: The NgStyle directive enables you to conditionally apply inline styles to HTML elements.
Syntax:
<div [ngStyle]="{'property': 'value'}">
<!-- Content here -->
</div>
3. ngModel: The NgModel directive provides two-way data binding for form elements, syncing data between the model and the view.
Syntax:
<input [(ngModel)]="property">
Example:
<!-- app.component.html -->
<div class="container">
<h1 class="title">w3wiki</h1>
<div class="content">
<div [ngClass]="{'highlight': isHighlighted, 'italic': isItalic}">
This div's classes are dynamically applied based on conditions.
</div>
<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">
This div's styles are dynamically applied based on properties.
</div>
<input type="text" [(ngModel)]="username" class="input-field">
<p class="greeting">Hello, {{ username }}!</p>
</div>
</div>
/* app.component.css */
.container {
text-align: center;
}
.title {
color: green;
}
.content {
margin-top: 20px;
}
.input-field {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.greeting {
margin-top: 20px;
}
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isHighlighted: boolean = true;
isItalic: boolean = false;
textColor: string = 'blue';
fontSize: number = 18;
username: string = '';
}
//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
Built-in directives in Angular
Directives are markers in the Document Object Model(DOM). Directives can be used with any controller or HTML tag which will tell the compiler what exact operation or behavior is expected. There are some directives present that are predefined but if a developer wants he can create new directives (custom-directive).
There are basically 3 types of directives and each type has some built-in directives. In this article, we will discuss all 3 types of directives and their built-in directives.
Table of Content
- 1. Component Directives
- 2. Attribute Directives
- 3. Structural Directives