I am here to continue the discussion around AngularJS 2.0. Today, we will discuss the output property binding in AngularJS 2. Also, in case, you did not have a look at the previous articles of this series, go through the links, mentioned below.
In my previous article, I already discussed about the different process of data binding techniques including input property binding mechanism and output property for the Event Emitter in case of components within Angular 2.0. Now, in this article, I will discuss about the Directive concept in Angular 2. Before starting discussion about directive in Angular 2, first of all, we need to understand what directive is. As per Google, Directives are markers on a DOM object model or element (such as an attribute, element name, comment or CSS Class) that tells AngularJS’s HTML compiler to attach a specified behavior to that DOM element or even to transform the DOM element and its child objects. Just like previous versions of Angular, Angular 2 also contains some built in directives and also allows us to create Custom Directives.
In Angular 2, basically the directives are also a component. Basically, there are three types of Directives in Angular 2, which are listed below.
- Components using @Component decorator is actually a directive with the template or template URL. I already discussed about this in my earlier articles in this series.
- Attribute Directives using @Directive decorator. It does not change DOM element but it changes the appearance of DOM element.
- Structural Directives using @Directive decorator. It can change DOM element or add any new DOM element or remove any DOM element.
In this article, we will discuss about the attribute Directives in Angular 2. The attribute Directive changes the appearance or behavior of a DOM element. These Directives look like regular HTML attributes in the templates and ngModel Directive, which is used for two-way is a perfect example of an attribute Directive. To create attribute Directives, we always need to use or inject the objects given below in our custom attribute Directive component class.
- ElementRef
While creating custom attribute Directive, we inject ElementRef in the constructor to access DOM element. Actually an ElementRef provides access to the underlying native element. ElementRef is a Service that grants us direct access to DOM element through its nativeElement property and we need to set the element’s color, using the Browser DOM API.
- Renderer
While creating custom attribute directive, we inject Renderer in the constructor to access DOM element’s style. Actually, we call the renderer’s setElementStyle function. In this function, we pass the current DOM element with the help of ElementRef object and set the required attribute of the current element.
- HostListener
Some times, we may need to access an input property within the attribute directive, so that as per the given attribute directive, we can apply the related attribute within DOM element. For trap user actions, we can call different methods to handle the user actions. To access the method to operate user actions, we need to decorate the methods within the @HostListener method.
There are some inbuilt attribute directives in Angular2 like ngClass, ngStyle, ngSwitch etc. In the program given below, we demonstrate, how to use this attribute in our component.
Step 1
First, we add a TypeScript file named app.component.colorchange.ts and add the code given below.
- import { Component, OnInit } from '@angular/core';
-
- @Component({
- moduleId: module.id,
- selector: 'attribute-directive',
- templateUrl: 'app.component.colorchange.html',
- styles: [".red {color:red;}", ".blue {color:blue}", ".cyan {color : cyan}"]
- })
-
- export class AttrDirectiveComponent implements OnInit {
- constructor() { }
- showColor: boolean = false;
- ngOnInit() { }
-
- changeColor(): void {
- this.showColor = !this.showColor;
- }
- }
Step 2
Now, add HTML file named
app.component.colorchange.html and add the code given below.
- <div>
- <h3>This is a Attribute Directives</h3>
- <span [class.red]="true">Attribute Change</span><br />
- <span [ngClass]="{'blue':true}">Attribute Change by Using NgClass</span><br />
- <span [ngStyle]="{'font-size':'14px','color':'green'}">Attribute Change by Using NgStyle</span>
- <br /><br />
- <span [class.cyan]="showColor">Attribute Change</span><br />
- <span [ngClass]="{'cyan':showColor}">Attribute Change by Using NgClass</span><br />
- <input type="button" value="Change Color" (click)="changeColor()" />
- <br /><br />
- <span [class.cyan]="showColor">Attribute Change</span><br />
- <span [ngClass]="{'cyan':showColor, 'red' : !showColor}">Attribute Change by Using NgClass</span><br />
- </div>
Step 3
Now, add another TypeScript file named app.module.ts and add the code given below.
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { AttrDirectiveComponent } from './src/app.component.attrdirective';
-
- @NgModule({
- imports: [BrowserModule],
- declarations: [AttrDirectiveComponent],
- bootstrap: [AttrDirectiveComponent]
- })
- export class AppModule { }
Step 4
Now add another HTML file named index.html and add the code given below.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Angular2</title>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="../styles.css">
- <!-- Polyfill(s) for older browsers -->
- <script src="../node_modules/core-js/client/shim.min.js"></script>
- <script src="../node_modules/zone.js/dist/zone.js"></script>
- <script src="../node_modules/reflect-metadata/Reflect.js"></script>
- <script src="../node_modules/systemjs/dist/system.src.js"></script>
- <script src="../systemjs.config.js"></script>
- <script>
- System.import('app').catch(function (err) { console.error(err); });
- </script>
- </head>
- <body>
- <attribute-directive>Loading</attribute-directive>
-
- </body>
- </html>
Now, run the code and output will be, as shown below. In the output, we create a button called change color on click of which it will execute a method and change the color of the element.
Now, we will create another table list type component, where on click on any table row, table background will be changed. For doing this, first we need to create a student list. For this, we will use ngSwitch directive.
Step 1
We need to add a typeScript file named hightlight.directive.ts, which basically performs the row highlight on row click.
- import { Directive, ElementRef, Renderer, HostListener, Input } from "@angular/core";
-
- @Directive({
- selector:"[highlight]"
- })
-
- export class Highlight {
- @Input("highlight") Color: string;
- constructor(private el: ElementRef, private renderer: Renderer) {
- this.renderer.setElementStyle(this.el.nativeElement, 'cursor', 'pointer');
- }
-
- @HostListener("click")
-
- onclick(): void {
- this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', this.Color);
- }
- }
Step 2
Now, create another TypeScript file named app.component.list.ts and write down the code given below.
- import { Component, OnInit, Directive } from '@angular/core';
-
- @Component({
- moduleId: module.id,
- selector: 'student-list',
- templateUrl: 'app.component.list.html'
- })
-
- export class ListComponent implements OnInit {
- studentList: Array<any> = new Array<any>();
-
- constructor() { }
- ngOnInit() {
- this.studentList = [
- { SrlNo: 1, Name: 'Rajib Basak', Course: 'Bsc(Hons)', Grade: 'A' },
- { SrlNo: 2, Name: 'Rajib Basak1', Course: 'BA', Grade: 'B' },
- { SrlNo: 3, Name: 'Rajib Basak2', Course: 'BCom', Grade: 'A' },
- { SrlNo: 4, Name: 'Rajib Basak3', Course: 'Bsc-Hons', Grade: 'C' },
- { SrlNo: 5, Name: 'Rajib Basak4', Course: 'MBA', Grade: 'B' },
- { SrlNo: 6, Name: 'Rajib Basak5', Course: 'MSc', Grade: 'B' },
- { SrlNo: 7, Name: 'Rajib Basak6', Course: 'MBA', Grade: 'A' },
- { SrlNo: 8, Name: 'Rajib Basak7', Course: 'MSc.', Grade: 'C' },
- { SrlNo: 9, Name: 'Rajib Basak8', Course: 'MA', Grade: 'D' },
- { SrlNo: 10, Name: 'Rajib Basak9', Course: 'B.Tech', Grade: 'A' }
- ];
- }
- }
Step 3
Create HTML file named app.component.list.html and add the code given below.
- <div>
- <h2>Demonstrate ngSwitch</h2>
- <table style="width:100%;border:solid;border-color:blue;border-width:thin;">
- <thead>
- <tr >
- <td>Srl No</td>
- <td>Student Name</td>
- <td>Course</td>
- <td>Grade</td>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let student of studentList;" highlight="red">
- <td>
- <span>{{student.SrlNo}}</span>
- </td>
- <td>
- <span >{{student.Name}}</span>
- </td>
- <td>
- <span >{{student.Course}}</span>
- </td>
- <td>
- <span >{{student.Grade}}</span>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
Step 4
Now, include the app.component.list.ts within the app.component.colorchange.ts file, as shown below.
- import { Component, OnInit } from '@angular/core';
- import { ListComponent } from './app.component.list';
Step 5
Now, add HTMLselector for stuldent list within app.component.colorchange.html file, as shown below.
- <div>
- <h3>This is a Attribute Directives</h3>
- <span [class.red]="true">Attribute Change</span><br />
- <span [ngClass]="{'blue':true}">Attribute Change by Using NgClass</span><br />
- <span [ngStyle]="{'font-size':'14px','color':'green'}">Attribute Change by Using NgStyle</span>
- <br /><br />
- <span [class.cyan]="showColor">Attribute Change</span><br />
- <span [ngClass]="{'cyan':showColor}">Attribute Change by Using NgClass</span><br />
- <input type="button" value="Change Color" (click)="changeColor()" />
- <br /><br />
- <span [class.cyan]="showColor">Attribute Change</span><br />
- <span [ngClass]="{'cyan':showColor, 'red' : !showColor}">Attribute Change by Using NgClass</span><br />
-
- <br />
- <student-list></student-list>
- </div>
Step 6
Now, include the 2 component files within app.module.ts file, as shown below.
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { AttrDirectiveComponent } from './src/app.component.attrdirective';
- import { Highlight } from './src/highlight.directive';
- import { ListComponent } from './src/app.component.list';
-
-
- @NgModule({
- imports: [BrowserModule],
- declarations: [AttrDirectiveComponent, Highlight, ListComponent],
- bootstrap: [AttrDirectiveComponent]
- })
- export class AppModule { }
Now, run the code, as shown below.