TL;DR;
Short guide on Angular Directives: Classes adding behaviours in Angular, with types, importance, examples, and a quiz to test your understanding covering:
In the vast world of Angular, these concepts play a pivotal role in shaping and controlling the behaviour of your applications. One of the key ingredients in this concoction is the Directive. Let’s delve deeper into this concept.
Directives are essentially classes that add specific behaviours to elements in the Angular framework. They can be thought of as instructions that guide Angular on how to manipulate the DOM (Document Object Model).
In Angular, there are three primary types of directives:
Directives offer developers the ability to:
Let's explore a simple use case: altering the colour of a paragraph based on user interaction. This can be adeptly handled using an attribute directive.
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: 'appHighlight'
})
export class HighlightDirective {
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;
}
}
Usage in HTML:
<p appHighlight>Hover over this text to highlight it!</p>
Upon hovering over the text, the directive activates, shading the paragraph in yellow. The color vanishes once the mouse pointer is moved away.
Which of the following is NOT a type of directive in Angular?
What is the primary element that Directives manipulate in Angular?
In the given code example, which decorator detects DOM events?
@DirectiveListener
@EventListener
@DOMListener
@HostListener
@HostListener
Directives offer a formidable suite of tools for developers navigating the Angular landscape. They infuse dynamism and reusability into web applications, positioning Angular as a top-choice framework in web development. Whether customizing behaviour or adjusting the DOM, directives are always at the developer's disposal.