Angular Directives
Angular Directives Interview with follow-up questions
1. What are Angular directives? Can you explain with an example?
Directives are classes that add behavior to elements in a template. Angular has three kinds: components (directives with a template), attribute directives (change an element's look/behavior), and structural directives (change DOM layout). Here's a custom attribute directive that highlights its host element:
import { Directive, ElementRef, inject } from '@angular/core';
@Directive({ selector: '[appHighlight]' }) // standalone by default
export class HighlightDirective {
private el = inject(ElementRef);
constructor() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}
<p>Highlighted text</p>
Note (important for 2026): the snippet some older guides show using angular.module(...).directive(...) is AngularJS (1.x) syntax and is obsolete — modern Angular uses the @Directive class above. Also, the classic structural directives *ngIf/*ngFor have been replaced by the built-in control flow @if/@for, so today you mostly write custom directives for reusable attribute behavior, optionally composed onto components via hostDirectives.
Follow-up 1
What are the different types of directives in Angular?
There are three types of directives in Angular:
Component Directives: These are directives with a template. They are used to create reusable UI components.
Structural Directives: These are directives that change the structure of the DOM by adding or removing elements. Examples include 'ngIf', 'ngFor', and 'ngSwitch'.
Attribute Directives: These are directives that change the behavior or appearance of an element. Examples include 'ngModel', 'ngStyle', and 'ngClass'.
Follow-up 2
Can you explain the difference between structural and attribute directives?
Structural directives are used to add or remove elements from the DOM based on a condition. They change the structure of the DOM. Examples of structural directives are 'ngIf', 'ngFor', and 'ngSwitch'.
Attribute directives, on the other hand, are used to change the behavior or appearance of an element. They don't change the structure of the DOM. Examples of attribute directives are 'ngModel', 'ngStyle', and 'ngClass'.
Follow-up 3
How do you create a custom directive in Angular?
To create a custom directive in Angular, you can use the 'directive' method of an Angular module. Here's an example:
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
template: 'Directive Example'
};
});
In this example, we have created a custom directive called 'myDirective' which replaces the content of the element with the text 'Directive Example'. The 'directive' method takes two arguments: the name of the directive and a factory function that returns the directive definition object. The directive definition object specifies the behavior of the directive, such as its template or link function.
2. What is the purpose of *ngIf directive in Angular?
*ngIf conditionally adds or removes an element (and its subtree) from the DOM based on an expression — when false, the element isn't hidden with CSS, it's genuinely not rendered. It also supports an else template via a `` reference:
<div>Hello {{ user().name }}</div>
Loading…
The crucial 2026 update: *ngIf is superseded by the built-in @if control flow (default since Angular 17), which is the recommended syntax for new code — no import needed, cleaner @else if/@else, and better performance:
@if (user(); as u) {
<div>Hello {{ u.name }}</div>
} @else {
<p>Loading…</p>
}
*ngIf still works, but mentioning that you'd reach for @if shows current knowledge. (Either way, remember it changes the DOM, unlike [hidden], which only toggles visibility.)
Follow-up 1
Can you provide a scenario where *ngIf directive can be used?
Sure! One scenario where *ngIf directive can be used is when you want to conditionally display or hide a specific element based on a certain condition. For example, you can use *ngIf to show a login form only if the user is not already logged in. Here's an example:
<div>
</div>
Follow-up 2
What is the difference between *ngIf and [hidden]?
The *ngIf directive and [hidden] attribute are both used to conditionally show or hide elements in Angular, but they have some differences:
*ngIf: When the condition is false, the element is completely removed from the DOM. This means that any associated event listeners or bindings are also removed. When the condition becomes true again, the element is re-rendered and any associated event listeners or bindings are re-initialized.
[hidden]: When the condition is false, the element is hidden using the CSS 'display: none' property. The element remains in the DOM, and any associated event listeners or bindings are still active. When the condition becomes true again, the element is shown by removing the 'display: none' property.
In general, if you need to completely remove an element from the DOM and re-initialize any associated event listeners or bindings, *ngIf is a better choice. If you just need to hide and show an element without affecting its event listeners or bindings, [hidden] can be used.
Follow-up 3
How does *ngIf directive affect the DOM?
The *ngIf directive in Angular affects the DOM by conditionally adding or removing elements from the DOM based on the evaluation of the expression. When the condition is true, the element is rendered and added to the DOM. When the condition is false, the element is removed from the DOM. This can be useful for optimizing performance, as elements that are not needed can be completely removed from the DOM, reducing the overall size and complexity of the DOM tree. Additionally, any associated event listeners or bindings are also removed when the element is not rendered, which can help prevent memory leaks and improve performance.
3. How does the *ngFor directive work in Angular?
*ngFor repeats a template once per item in an iterable, exposing locals like index, first, last, even, odd:
<li>
{{ i }}: {{ item.name }}
</li>
The performance point interviewers probe is trackBy: without it, Angular re-renders list items when the array reference changes; with a stable identity function it reuses DOM nodes, avoiding costly re-creation.
The key 2026 update: *ngFor is replaced by the built-in @for (default since Angular 17), where track is mandatory (so good performance is the default) and there's a built-in @empty block:
@for (item of items; track item.id; let i = $index) {
<li>{{ i }}: {{ item.name }}</li>
} @empty {
<li>No items</li>
}
Prefer @for in new code; *ngFor still works for legacy templates.
Follow-up 1
Can you explain the syntax of *ngFor directive?
The syntax of the *ngFor directive in Angular is as follows:
- The 'container-element' is the HTML element that will be repeated for each item in the iterable.
- The 'item' is a local variable that represents the current item in the iteration.
- The 'iterableExpression' is an expression that evaluates to an iterable, such as an array or an object.
- The 'index' is an optional local variable that represents the index of the current item in the iteration.
Follow-up 2
How can you track items in *ngFor directive for performance optimization?
In order to track items in the *ngFor directive for performance optimization, you can use the 'trackBy' function. The 'trackBy' function allows Angular to track the identity of each item in the iterable, so that it can reuse and reorder the corresponding DOM elements instead of recreating them.
Here is an example of how to use the 'trackBy' function:
In the component class, you need to define the 'trackByFunction' that takes the index and the item as arguments and returns a unique identifier for the item. This unique identifier can be a property of the item or a combination of multiple properties.
trackByFunction(index: number, item: any): any {
return item.id;
}
Follow-up 3
What is the role of 'index' in *ngFor directive?
The 'index' is an optional local variable in the *ngFor directive that represents the index of the current item in the iteration. It can be used in the template code to access the index of each item.
Here is an example of how to use the 'index' variable:
<p>Item {{ index }}: {{ item }}</p>
In this example, the 'index' variable is used to display the index of each item in the iteration. The output will be:
Item 0: Item 1
Item 1: Item 2
Item 2: Item 3
Note that the 'index' variable starts from 0 for the first item and increments by 1 for each subsequent item.
4. What is the role of ngSwitch directive in Angular?
ngSwitch renders one of several templates based on a value — like a switch statement in the DOM. It's used as a trio: [ngSwitch] on a container with *ngSwitchCase and *ngSwitchDefault on the children:
<div>
<p>Loading…</p>
<p>Something went wrong</p>
<p>Ready</p>
</div>
The 2026 update to mention: this is replaced by the built-in @switch control flow (default since Angular 17), which is cleaner and needs no extra wrapper element:
@switch (status) {
@case ('loading') { <p>Loading…</p> }
@case ('error') { <p>Something went wrong</p> }
@default { <p>Ready</p> }
}
ngSwitch still works, but @switch is the recommended modern syntax.
Follow-up 1
Can you explain the syntax of ngSwitch directive?
The syntax of ngSwitch directive in Angular is as follows:
Content to display when expression matches value1
Content to display when expression matches value2
Content to display when expression does not match any case
Here, expression is the value to be evaluated, value1 and value2 are the possible values that the expression can match, and the content within the *ngSwitchCase elements is displayed when the expression matches the corresponding value. The content within the *ngSwitchDefault element is displayed when the expression does not match any of the cases.
Follow-up 2
How does ngSwitch directive compare with *ngIf directive?
The ngSwitch directive and the *ngIf directive in Angular are used for conditional rendering of content, but they have some differences:
- The ngSwitch directive is used when there are multiple possible cases to match against, whereas the *ngIf directive is used for a single condition.
- The ngSwitch directive evaluates the expression once and then displays the content associated with the matching case, whereas the *ngIf directive evaluates the condition on every change detection cycle.
- The ngSwitch directive can have multiple *ngSwitchCase elements to define different cases, whereas the *ngIf directive only has a single condition.
- The ngSwitch directive also has a *ngSwitchDefault element to define the content to display when none of the cases match, whereas the *ngIf directive does not have a default case.
Follow-up 3
Can you provide a scenario where ngSwitch directive can be used?
The ngSwitch directive can be used in various scenarios where you want to conditionally display different content based on a given expression. For example, you can use ngSwitch to display different views or components based on the selected option in a dropdown menu. Here is an example:
Option 1
Option 2
Option 3
<div>
<div>Content for Option 1</div>
<div>Content for Option 2</div>
<div>Content for Option 3</div>
<div>Default Content</div>
</div>
5. How do you bind to directive properties in Angular?
You bind to a directive's (or component's) inputs with property binding — the same [prop] syntax used on native elements. The directive declares the input, and the template passes a value:
@Directive({ selector: '[appTooltip]' })
export class TooltipDirective {
text = input(''); // signal input (modern)
// or: @Input() text = ''; // decorator input (classic)
}
Hover me
Hover me
The modern detail worth adding: prefer the signal input input() over @Input() in new code — it gives a reactive, read-only signal you can use in computed()/effect(), plus input.required() for mandatory inputs and a built-in transform option. For two-way binding to a directive/component property, use the model() API with [(prop)].
Follow-up 1
What is the role of @Input decorator in directive property binding?
The @Input decorator in Angular is used to define an input property for a directive. It allows the parent component to bind to the directive's property using the property binding syntax.
For example, if you have a directive called MyDirective with a property called myProperty, you can define it as an input property using the @Input decorator like this:
@Input() myProperty: string;
Now, the parent component can bind to this property using the property binding syntax:
In this example, parentData is a variable in the parent component that you want to pass to the myProperty property of the MyDirective directive.
Follow-up 2
Can you explain with an example how to bind to directive properties?
Sure! Here's an example of how to bind to directive properties in Angular:
Let's say you have a directive called MyDirective with a property called myProperty. In the parent component, you have a variable called parentData that you want to pass to the myProperty property of the MyDirective directive.
You can bind to the directive property using the property binding syntax like this:
In this example, parentData is the variable in the parent component that you want to pass to the myProperty property of the MyDirective directive.
Follow-up 3
What is the difference between property binding and attribute binding in Angular?
In Angular, property binding and attribute binding are two different ways to bind data to an element.
Property binding is used to bind to a property of an element or a directive. It uses the square bracket syntax ([property]="value") and allows you to pass data from the component to the element or directive.
Attribute binding, on the other hand, is used to bind to an attribute of an element. It uses the normal attribute syntax (attribute="value") and allows you to pass data from the component to the element.
The main difference between property binding and attribute binding is that property binding is used for binding to properties of elements or directives, while attribute binding is used for binding to attributes of elements.
Live mock interview
Mock interview: Angular Directives
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.