Directives are just an instruction to the compiler (like components ,selectors of html tags) which tell Angular 2 what to do at certain places in your code. Directives are key parts which not only allow us to render views with the help of components but also allow us to change the general appearance and also the structure of the DOM.
So in this blog post, we will learn how to use Directives in Angular 2.
Essentially, there are three types of directives in Angular 2 as shown in the figure below.
Attribute Directives
They interact with the element to which they are applied.(e.g. change the style). They are named attribute directives because they are applied like a HTML element attribute. For Example ( ).
Note
Directives don't have Property or Event Bindings.
Example of Attribute Directives are as follows:
First create one component using angular-cli. which will create boiler plate for us; for example, if we are creating a component with the help of the following command
cmd > ng g c directives
It will create directives.component.html,directives.component.css,
directives.component.ts,directives.component.spec.ts
Now change .css file and write the following code.
- .border {
- border: 3 px solid blue;
- }.background {
- background - color: green;
- }
- div {
- width: 100 px;
- height: 100 px;
- }
Then in .html file write these.
- <h1>Attribute Directives</h1>
- <h2>ngClass/ngStyle</h2>
- <div [ngClass]=”{border: false, background: true}”></div>
And Output will be
- ngStyle
- <h1>Attribute Directives</h1>
- <h2>ngClass/ngStyle</h2>
- <div [ngStyle]=”{‘background-color’: ‘red‘}”></div>
And Ouput will be
Example of Custom Attribute Directive ( Highlighter )
First we need to add directive with the following command:
cmd > ng g d highlighterdirective
Which will create basic directive for us.
Change the directive with the following code:
- import {
- Directive,
- HostBinding,
- HostListener,
- Input,
- OnInit
- } from '@angular/core';
- @Directive({
- selector: '[apphighlighter]'
- })
- export class HighlighterDirective {
- private backgroundColor: string;
- @Input() defaultColor = 'white';
- @Input('apphighlighter') highlightColor = 'green';
- constructor() {}
- ngOnInit() {
- this.backgroundColor = this.defaultColor;
- }
- @HostListener('mouseenter') mouseover() {
- this.backgroundColor = this.highlightColor;
- }
- @HostListener('mouseleave') mouseleave() {
- this.backgroundColor = this.defaultColor;
- }
- @HostBinding('style.backgroundColor') get setColor() {
- return this.backgroundColor;
- }
- }
So in the above example we need to focus on certain things which are mentioned below:
- Import HostListener,HostBinding,Input and OnInIt from @angular/core.
- We had created properties defaultColor and highlightColor with the help of @ Input that means it can be set from outside also so that it can be used in any component.
Now we need to declare the Directives to app.module
First we need to import the directives to app.module.ts
- import {
- HighlighterDirective
- } from './highlighter.directive';
- then In app.module.ts we need to declare it in declaration array
- @NgModule({
- declarations: [
- AppComponent,
- HighlighterDirective
- ],
- now we can use it on our.html page like this < h2 > Custom Attribute Directives < /h2> < div[apphighlighter] = ”’blue’”[defaultColor] = ”‘red‘“ > Some Text < /div>
Structural Directives
They interact with the current view Container and change the structure of the DOM/HTML code. They are named structural directives because they change the structure of the DOM. For Example ( *ngIf,*ngFor,*ngSwitch).
All structural directives are prefix with *
All structural directives are prefix with *
- *ngIf
- <h1>Structural Directives</h1>
- <h2>*ngIf</h2>
- <div *ngIf=”switch”>Conditional Text</div> <button (click)=”onSwitch()”>Switch</button>
In Your .ts file
- import {
- Component,
- OnInit
- } from '@angular/core';
- @Component({
- selector: 'app-tasks',
- templateUrl: './tasks.component.html',
- styleUrls: ['./tasks.component.css']
- })
- export class TasksComponent implements OnInit {
- private
- switch = true;
- onSwitch() {
- this.switch = !this.switch;
- }
- }
in this example of *ngIf , i had created one button which acts like a toggle button. Onclik it will hide the content and vice a versa.
On Click it will remove the conditional text div
- *ngFor (Simple)
- <h2> *ngFor </h2>
- <ul>
- <li *ngFor=”let item of items”>{{item}}</li>
- </ul>
In Your .ts file
- import {
- Component,
- OnInit
- } from '@angular/core';
- @Component({
- selector: 'app-tasks',
- templateUrl: './tasks.component.html',
- styleUrls: ['./tasks.component.css']
- })
- export class TasksComponent implements OnInit {
- private items = {
- 1,
- 2,
- 3,
- 4,
- 5];
- }
It will loop through the items array an bind each element with li .
- *ngFor(With Index)
- <h2> *ngFor </h2>
- <ul>
- <li *ngFor=”let item of items; let i=i ndex”>{{item}}- (Index :{{i}}) </li>
- </ul>
It will loop through the same items array but also with the index of the elements.
Conclusion
In this post we learned about Some Directives in Angular 2, and created them. I hope you find this post useful. Thanks for reading! Cheers.