Angular Attribute Directives
An attribute directive adds a reusable behavior or host binding to an existing element. Use it when the element should keep its own identity and semantics.
How it works
UrgentDirective exposes a boolean input and reflects it through a host class. The caller keeps the paragraph, while the directive provides one reusable presentation rule. A directive should have a narrow contract and clean up any listeners or subscriptions it creates. For a whole reusable view with its own structure, a component is usually the more appropriate abstraction.
Run the code
Use a separate empty project folder with a compatible Node version: ^22.22.3, ^24.15.0 or a supported 26+ runtime. The review uses Node 24.22.1, Angular 22.2.4, CLI/build 22.2.5 and TypeScript 6.0.3. Node 22.15.1 is too old for Angular 22. Save every download at its displayed path; browsers may keep only the basename, so recreate the src folder. Run npm install, npm run build and npm start, then open the loopback address printed by the server. Run npm test for the supplied component tests. These are local teaching projects, not Bhylu publishing files.
The small loopback server serves the compiled app and fixed, read-only tool API fixtures. It is not a database, authentication or lending service. Angular examples do not run in Bhylu’s current HTML or TypeScript playground. No Apache, MySQL or PHP configuration change is needed.
Example
import { Component } from '@angular/core';
import { Directive, input } from '@angular/core';
@Directive({
selector: '[bhUrgent]',
standalone: true,
host: { '[class.urgent]': 'urgent()' },
})
class UrgentDirective {
urgent = input(false);
}
@Component({
selector: 'bh-directives',
standalone: true,
imports: [UrgentDirective],
template: `<p bhUrgent [urgent]="true" data-result>Safety check required</p>`,
styles: [
`
.urgent {
font-weight: 600;
}
`,
],
})
export class App {}
Expected result
Safety check required
The paragraph receives the urgent class because its directive input is true. The browser review checks the actual class on the original element. CSS communicates emphasis visually, while the wording remains meaningful without depending only on color.