Directives — Angular Technical Interview Questions & Answers
Directives
Directives
- A directive changes an existing element. Attribute directive: highlight Fail rows. Structural: *ngIf / *ngFor add or remove nodes. Components are directives with a template.
- Write @Directive({ selector: '[appFail]' }) and HostBinding('class.fail'). Use it as <tr appFail>. Don’t build a whole component just to add a class.
- Trap: putting business rules inside a directive that should live in a service. Directives are for the DOM.
Technical Interview Tip: Attribute vs structural. One HostBinding example.
Code Examples for Directives
Directives — working example
// template
// <p *ngIf="ok">Visible</p>
// <li *ngFor="let u of users">{{ u }}</li>
users = ["Asha", "Ravi"];
ok = true;Directives — *ngIf toggles DOM; *ngFor repeats a template per item.
How to Explain Directives to an Interviewer
Directive vs component?
Directive: no template / changes host Component: has template
Name two structural directives.
*ngIf *ngFor