Directives in angular are custom tags and custom attributes of html which is controlled by class and decorators. Using directives we can change the behaviour, style and logic of a specific area.
Example:
helloworld.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: ‘hello-world’,
template: ‘Hello world component/directive’
})
export class HelloWorld implements OnInit {
constructor() {
}
ngOnInit() {
}
}
Xyz.compenent.html
<hello-world></hello-world>
Output:Hello world component/directive
Types of Directives in Angular:
- Component
- Attributes Directive
- Structural Directive
1. Component :
Angular page is group of components, we use component everywhere in the angular project. so, we can say that components are main part of an angular application.
Component contains decorators and class. Decorator contains the details of html template, css, change detection strategy and the component selector name.
Let’s create a component using ng generate command
ng g component helloworld
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: ‘hello-world’,
template: ‘Hello world component/directive’
})
export class HelloWorld implements OnInit {
constructor() {
}
ngOnInit() {
}
}
2. Attribute Directive
Attribute directive is used the change the behaviour of element, component or directive. there is some in-build structural directive ngStyle, ngClass, ngModel.
Example:
<div [ngClass]="isActive ? 'active' : ''">This div is active container</div>
3. Structural Directive
Structural directives are directives which add or remove the elements from the dom.
There is 3 in-built structural directives in angular.
- ngFor
- ngIf
- ngSwitch
Example:
<hello-world *ngIf="isActive" [post]="post"></hello-world>