I think directives are the most important bit in an Angular application. There are 3 types of directive in Angular which is listed below.
- Component Directive
- Attribute Directive
- Structural Directive
Component Directive:
The component directive is something which is the core thing of angular application. We create components by using @Component decorator. The best example of component directive is AppComponent.
1
2
3
4
5
6
7
8
9
10
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
|
Attribute Directive:
Creating a directive is pretty similar to a component, we user @Directive decorator for creating the directives. Attribute directives are used as attributes of elements. Let me explain this with an example:
I wanted something like if I hover the mouse on paragraph then it's background should get changed. I also wanted to do something when someone clicks in the paragraph. Let's create a directive by name ParagraphColor by running below command. Once you run the below command, it'll automatically add the ParagraphColorDirective entry in declarations in the app.module.ts.
1
|
ng g d ParagraphColor
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appParagraphColor]'
})
export class ParagraphColorDirective {
@Input('appParagraphColor') paragraphColor: string;
constructor(private el: ElementRef) { }
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.paragraphColor);
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
@HostListener('click') onclick() {
alert('clicked')
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
|
Here in the above code snippet, we have a directive whose selector is appParagraphColor. We have been used @HostListener to listen to mouse events. We have created an object of ElementRef which will help us to set the background color of the paragraph.
In the above example, we have used mouseenter, mouseleave and click events. On mouse enter, we call the highlight function to set the background. We have passed/Input the color name from the component.
1
2
3
4
5
6
7
8
9
10
11
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'directives';
color: string = 'yellow';
}
|
In the app component, we have defined the color name and passing the color to the directive in the below code.
1
|
<p [appParagraphColor]="color">Coding 4 Developers</p>
|