Attribute Directives
7 min read
Attribute Directives
While structural directives change the DOM layout, attribute directives change the appearance or behavior of an existing element. Angular ships with NgClass, NgStyle, and others. You can also write your own custom attribute directives.
ts
import { Component } from '@angular/core';
import { NgClass, NgStyle } from '@angular/common';
@Component({
selector: 'app-status-badge',
standalone: true,
imports: [NgClass, NgStyle],
template: `
<span
[ngClass]="{
badge: true,
'badge-success': status === 'active',
'badge-warning': status === 'pending',
'badge-danger': status === 'error'
}"
[ngStyle]="{ 'font-weight': isBold ? 'bold' : 'normal' }"
>
{{ status }}
</span>
`
})
export class StatusBadgeComponent {
status: 'active' | 'pending' | 'error' = 'active';
isBold = true;
}Writing a Custom Attribute Directive
ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
@Input() appHighlight = 'yellow';
constructor(private el: ElementRef) {}
@HostListener('mouseenter')
onMouseEnter() {
this.el.nativeElement.style.backgroundColor = this.appHighlight;
}
@HostListener('mouseleave')
onMouseLeave() {
this.el.nativeElement.style.backgroundColor = '';
}
}Use @HostListener to respond to events on the host element without manually adding and removing event listeners. Angular cleans them up automatically when the directive is destroyed.
Ready to test yourself?
Practice Angular— quiz & coding exercises