Directives are used to extend the HTML syntax and provide additional functionality to elements in the DOM. Directives can be used to add behavior to an existing element, create a new element, or modify the behavior of an existing element. Here is an example of how to use directives in Angular:
1. Built-in Directives: Angular comes with some built-in directives, including ngIf and ngFor.
ngIf Directive: The ngIf directive is used to conditionally render an element based on a condition. For example, if we have a boolean variable named showElement, we can use the ngIf directive to show an element only if showElement is true.
<div *ngIf="showElement">This element will only be shown if showElement is true</div>
ngFor Directive: The ngFor directive is used to iterate over a collection and render an element for each item in the collection. For example, if we have an array of items, we can use the ngFor directive to render a list of items.
<ul>
<li *ngFor="let item of items">{{item}}</li>
</ul>
2. Custom Directives: In addition to the built-in directives, Angular allows you to create custom directives.
Here is an example of a custom directive that changes the background color of an element when it is clicked:
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[clickable]'
})
export class ClickableDirective {
@HostBinding('style.backgroundColor') backgroundColor: string;
@HostListener('click') onClick() {
this.backgroundColor = 'blue';
}
}
In the above example, we are creating a directive named clickable that changes the background color of an element when it is clicked. The @HostBinding decorator is used to bind the backgroundColor property to the style.backgroundColor property of the element. The @HostListener decorator is used to listen for the click event on the element and change the backgroundColor property.
We can use this directive in our HTML as follows:
<div clickable>This element will change its background color when clicked</div>
When the user clicks on the element, the background color will change to blue.
Thanks For reading.
Any Queries please comment.
Top comments (0)