Example of Attribute Directives
Now let us take an example to understand both built-in attribute directives and also custom directives.
Step 1: Create a new angular project
ng new project
Step 2. To generate a new directive, we can use the following command.
ng generate directive upperCase
Folder Structure :
Dependencies:
"dependencies": {
"@angular/animations": "~13.0.0-next.0",
"@angular/common": "~13.0.0-next.0",
"@angular/compiler": "~13.0.0-next.0",
"@angular/core": "~13.0.0-next.0",
"@angular/forms": "~13.0.0-next.0",
"@angular/platform-browser": "~13.0.0-next.0",
"@angular/platform-browser-dynamic": "~13.0.0-next.0",
"@angular/router": "~13.0.0-next.0",
"rxjs": "~7.4.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~13.0.0",
"@angular/cli": "~13.0.0",
"@angular/compiler-cli": "~13.0.0-next.0",
"@types/jasmine": "~3.10.0",
"@types/node": "^12.11.1",
"jasmine-core": "~3.10.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.4.3"
}
3. Implement the logic
<!-- app.component.html -->
<form>
<div>
<label>Name: </label>
<input
appUpperCase
type="text"
name="name"
minlength="4"
[(ngModel)]="name"
#nameInput="ngModel"
required
[ngClass]="{ 'is-invalid': nameInput.touched && nameInput.invalid }"
/>
<div *ngIf="nameInput.touched && nameInput.invalid">
Minimum length of name is 4 characters
</div>
</div>
<div>
<label>Age: </label>
<input
type="number"
name="age"
[(ngModel)]="age"
#ageInput="ngModel"
required
[ngStyle]="{
'border-color': ageInput.invalid && ageInput.touched ? 'red' : ''
}"
/>
<div *ngIf="ageInput.touched && ageInput.invalid">Age is required</div>
</div>
</form>
//app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
name: string = '';
age!: number;
}
//upper-case.directive.ts
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[appUpperCase]',
})
export class UpperCaseDirective {
constructor(private el: ElementRef) { }
@HostListener('input')
onInput(event: any) {
const input = this.el.nativeElement.value.toUpperCase();
this.el.nativeElement.value = input;
}
}
Output:
Attribute Directives in Angular
Attribute directives are a powerful tool that allows you to manipulate the behavior and appearance of HTML elements. In this article, you will see the fundamentals of attribute directives.
Table of Content
- What are Attribute Directive?
- Benefits of Attribute Directive
- Types of Attribute Directives
- Steps to create Custom Directives
- Example of Attribute Directives