Attribute Directives in Angular
Attribute directives in Angular are used to change the appearance or behavior of a DOM element. This tutorial covers the basics of attribute directives and how to use them effectively in your Angular applications.
What are Attribute Directives?
Attribute directives are Angular directives that modify the behavior or appearance of an element, component, or another directive. They are typically applied to elements as attributes.
Common Attribute Directives
Some of the common built-in attribute directives in Angular include:
ngClass: Adds and removes a set of CSS classes.ngStyle: Adds and removes a set of inline styles.ngModel: Binds an input, select, textarea, or custom form control to a property in the component.
Using ngClass
The ngClass directive adds and removes CSS classes dynamically:
<div [ngClass]="{'highlight': isHighlighted}">Highlight me!</div>
export class AppComponent {
isHighlighted = true;
}
Using ngStyle
The ngStyle directive adds and removes inline styles dynamically:
<div [ngStyle]="{'color': textColor}">Color me!</div>
export class AppComponent {
textColor = 'blue';
}
Using ngModel
The ngModel directive binds an input element to a property in the component:
<input [(ngModel)]="name">
<p>Hello, {{ name }}!</p>
export class AppComponent {
name = 'Angular';
}
Creating Custom Attribute Directives
You can create custom attribute directives by implementing the Directive decorator and the HostListener and HostBinding decorators:
import { Directive, ElementRef, Renderer2, HostListener, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor: string;
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.backgroundColor = 'yellow';
}
@HostListener('mouseleave') onMouseLeave() {
this.backgroundColor = null;
}
}
Using the Custom Directive
<div appHighlight>Hover over me to highlight!</div>
export class AppComponent {}
Key Points
- Attribute directives modify the behavior or appearance of an element, component, or another directive.
- Common built-in attribute directives include
ngClass,ngStyle, andngModel. - You can create custom attribute directives using the
Directivedecorator and theHostListenerandHostBindingdecorators.
Conclusion
Attribute directives in Angular are powerful tools for modifying the behavior and appearance of elements. By understanding and using attribute directives effectively, you can create more dynamic and interactive Angular applications. Happy coding!
