Angular directives allow you to attach new behavior to DOM elements by using metadata properties:
Metadata Properties:
Whenever you need to add personalized behavior to an element.
For example:
We need to create a component that will be attached
@Directive({
selector: "[hover]",
host: {
"(mouseover)": "onHover($event.target)"
}
})
export class HoverDirective {
onHover(btn) {
console.log(btn);
}
}
We just created a directive that can be used by adding selector hover
to any element.
That’s it, you just need to add the selector that was used when the directive was created. Magic happens when we hover over that element and our super onHover methods is invoked.
@Directive({
selector: "[hover-with-color]",
host: {
"(mouseover)": "onHover($event.target)"
},
inputs: ["color"],
outputs: ["colorChanged"]
})
export class HoverWithColorDirective {
color: string;
colorChanged: EventEmitter<string> = new EventEmitter<string>();
constructor(private el: ElementRef, private renderer: Renderer2) {}
onHover(element: any) {
if (element.style.color === this.color) {
this.renderer.setStyle(element, "color", "#000");
} else {
this.renderer.setStyle(element, "color", this.color);
}
this.colorChanged.emit(element.style.color);
}
}
In the above example we defined metadata properties for input and output. Using this properties we are able to receive and emit values based on some events that occur when we hover over our element.
<h1 hover-with-color color="rgb(255, 255, 255)"
(colorChanged)="onColorChanged($event)">
Hello
</h1>
Our working examples are here: