Angular Directives
What is a directive in Angular?
A directive in Angular is a special type of class that allows you to modify the behavior or appearance of DOM elements. Angular provides two main types of directives: structural and attribute directives. Structural directives modify the structure of the DOM, while attribute directives modify the appearance or behavior of existing elements.
What are the different types of directives in Angular?
Angular provides three types of directives:
- Components: Technically, components are directives with templates. They control a section of the view and can modify the DOM using data binding and event binding.
- Structural directives: These directives modify the structure of the DOM by adding or removing elements. Examples include
*ngIf,*ngFor, and*ngSwitch. - Attribute directives: These directives modify the appearance or behavior of an element without changing the structure of the DOM. Examples include
ngClass,ngStyle, and custom attribute directives.
What is a structural directive in Angular?
Structural directives are a type of directive in Angular that change the structure of the DOM by adding or removing elements based on a condition or data. They are typically used with the * symbol to signify that they modify the DOM structure.
Common structural directives include:
- *ngIf: Conditionally adds or removes an element based on an expression.
- *ngFor: Loops through a collection and creates an element for each item in the collection.
- *ngSwitch: Adds or removes elements based on the value of an expression, allowing different views based on a condition.
How does *ngIf work in Angular?
*ngIf is a structural directive that conditionally includes or excludes an element from the DOM based on a boolean expression. If the expression evaluates to true, the element is included; otherwise, it is removed from the DOM.
Example of *ngIf:
export class ExampleComponent {
isVisible = true;
}
<div *ngIf="isVisible">This is visible</div>In this example, the div element is displayed only if the isVisible property is true.
How does *ngFor work in Angular?
*ngFor is a structural directive that repeats an element for each item in a collection. It is commonly used to display lists of items in a template.
Example of *ngFor:
export class ExampleComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>In this example, *ngFor loops through the items array and creates a list item for each element in the array.
How does *ngSwitch work in Angular?
*ngSwitch is a structural directive that adds or removes elements from the DOM based on the value of an expression. It works in combination with *ngSwitchCase and *ngSwitchDefault to conditionally display different elements.
Example of *ngSwitch:
export class ExampleComponent {
viewMode = 'list';
}
<div [ngSwitch]="viewMode">
<div *ngSwitchCase="'list'">List View</div>
<div *ngSwitchCase="'grid'">Grid View</div>
<div *ngSwitchDefault>Default View</div>
</div>In this example, the component displays the appropriate view based on the value of the viewMode property.
What is an attribute directive in Angular?
Attribute directives in Angular are used to modify the appearance or behavior of an element, component, or another directive. Unlike structural directives, they do not change the DOM structure but instead change the way an element is styled, behave, or interact with the user.
Common attribute directives include:
- ngClass: Adds or removes classes from an element dynamically based on an expression.
- ngStyle: Sets the inline styles for an element dynamically based on an expression.
- Custom attribute directives: User-defined directives to modify element behavior.
How does ngClass work in Angular?
ngClass is an attribute directive that allows you to add or remove CSS classes on an element based on an expression. It can take a string, an object, or an array to apply classes dynamically.
Example of ngClass:
export class ExampleComponent {
isActive = true;
}
<div [ngClass]="{ 'active': isActive }">This div is active</div>In this example, the active class is applied to the div only if isActive is true.
How does ngStyle work in Angular?
ngStyle is an attribute directive that allows you to set inline styles for an element dynamically based on an expression. You can pass an object containing CSS properties and values to apply the styles conditionally.
Example of ngStyle:
export class ExampleComponent {
isHighlighted = true;
}
<div [ngStyle]="{ 'background-color': isHighlighted ? 'yellow' : 'white' }">
This div is highlighted
</div>In this example, the background color of the div is set to yellow if isHighlighted is true, otherwise, it is set to white.
How do you create a custom directive in Angular?
To create a custom directive in Angular, you use the @Directive decorator and define the logic inside a class. Custom attribute directives allow you to extend or modify the behavior of elements, components, or other DOM elements.
Steps to create a custom directive:
- Generate a directive using Angular CLI:
ng generate directive my-directive. - Use the
@Directivedecorator to define the directive. - Implement any desired behavior in the directive class.
Example of a custom directive:
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
In this example, the HighlightDirective sets the background color of the host element to yellow.
How do you use a custom directive in a template?
To use a custom directive in a template, simply apply the directive's selector as an attribute to an HTML element. The behavior defined in the directive will be applied to the element.
Example of using a custom directive:
<p appHighlight>This paragraph is highlighted!</p>In this example, the appHighlight directive is applied to the paragraph, and the background color will be set to yellow as defined in the directive.
What is the ElementRef class, and how is it used in directives?
ElementRef is a wrapper around a native DOM element in Angular. It provides direct access to the underlying DOM element, which can be used in directives to manipulate the element or interact with its properties.
Example of using ElementRef in a directive:
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
this.highlight('yellow');
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
In this example, the ElementRef is used to access the native element and apply the highlight function to change its background color.
What is the HostListener decorator, and how is it used in directives?
The @HostListener decorator in Angular is used to listen for DOM events on the host element to which the directive is applied. It allows you to handle events such as clicks, mouse movements, or key presses within the directive class.
Example of using HostListener:
@Directive({
selector: '[appHoverHighlight]'
})
export class HoverHighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
In this example, the @HostListener decorator is used to listen for mouseenter and mouseleave events, changing the background color when the user hovers over the element.
What is the HostBinding decorator, and how is it used in directives?
The @HostBinding decorator in Angular is used to bind a property of the host element to a directive's property. It allows you to dynamically set host element properties, such as styles, classes, or attributes, based on the directive's logic.
Example of using HostBinding:
@Directive({
selector: '[appTextColor]'
})
export class TextColorDirective {
@HostBinding('style.color') textColor: string;
constructor() {
this.textColor = 'blue';
}
}
In this example, the @HostBinding decorator is used to bind the color style of the host element to the textColor property of the directive.