TU Tran

Technologies should serve for business purpose.


Angular2 - Directives - Part 2

Where can I see Angular2 - Directives - Part 1?

Please have a look at Angular2 - Directives - Part 1 for more information about part 1.

Ok, I have been read through part 1, But still not understand which case we should use attribute directive, could you tell me?

Attribute directive is a suitable solution when we want to modify current behavior or append new feature to HTML tag.

Let look at screenshot below:

To show this tooltip, we need to set title property of html tag as:

 In the case, we want to change behavior of  a tag. I mean, hovering on this tag will show the tooltip as:

So, we need to define new tooltip directive (this is attribute directive), this directive will modify default behavior of a tag. In the code, we change to:

In this code, we add new tooltip attribute of a tag.

Can I register event listener of DOM element which my directive attached to?

Yes, Inside directive we can register event listener on DOM element which our directive attached to, as sample below:

Let change behavior of our HightlightBaseOnFirstName directive. Appropriated color will be set to background of DOM element.

export class HightlightBaseOnFirstName {
    @Input() color: string = "white";
    @Input() text: string = "Tu";
    private dom: any = null;
    constructor(ui: ElementRef) {
        this.dom = ui.nativeElement;
    @HostListener('mouseenter') onMouseEnter() {
        this.dom.style.backgroundColor = this.color;
    @HostListener('mouseleave') onMouseLeave() {
        this.dom.style.backgroundColor = "";

In this code, we add 2 new listener named mouseenter and mouseleave. These are the same meaning as mouseenter and mouseleave event of DOM element.

Let compile and run the app again. We see that the background is white by default, it was changed when hovering on first-name as below:

Ok great, How about Component (directives with a template)?

We use this type of directive in the case we want to re-use the whole region with it own business logic.

In out example, the summary section can be implemented as component and use it in users.html file.

Ok, Can you show me how to do this?

Ok, Let do this.

I create new component named "user-detail" as below:

add new userDetail.html:

<div *ngIf="user!=null">
    <h3>Summary of {{user.firstName}}</h3>
    <form class="form-horizontal form-label-left ">
        <div class="form-group ">
            <label>First Name</label>
            <input class="form-control " [(ngModel)]="user.firstName " name="first " />
        <div class="form-group ">
            <label>Last Name</label>
            <input class="form-control " [(ngModel)]="user.lastName " name="last " />

and userDetail.ts:

import {Component, Input} from "@angular/core";
    selector: "user-detail",
    templateUrl: "src/userDetail.html"
export class UserDetail {
    @Input() user: any = null;

Then, we update users.html as below:

In users.html, we replace a lot of markup by single line. "user-detail" must match with "selector" property of UserDetail directive.

By this way, we can divide a complex page into alot of smaller directives. Each directive has its own responsibility, re-usable component/ directive and the code is easier for maintenance in the future.

How about passing Input and Output parameter?

This works the same as attribute directive. Please have a look at Angular2 - Directives

How about other attribute of component as directive?

This work the same as component in angular. for more information, see Angular2 - Component

 And how about Structural Directive?

A Structural directive changes the DOM layout by adding and removing DOM elements. As the sample below, we use NgIf for displaying a part of content of the page:

<div *ngIf="user!=null">
    <h3>Summary of {{user.firstName}}</h3>
    <form class="form-horizontal form-label-left ">
        <div class="form-group ">
            <label>First Name</label>
            <input class="form-control " [(ngModel)]="user.firstName " name="first " />
        <div class="form-group ">
            <label>Last Name</label>
            <input class="form-control " [(ngModel)]="user.lastName " name="last " />

Let run the app, at the first time, user property was null:

In this case, <user-detail> is empty.

Now, let try to select a user, and check again:

A new DOM appropriated to "User Summary" section was added into "<user-detail>". This is how NgIf (Structural Directive) works.

Is there any other structural directive?

There are some others, such as: NgFor, NgSwitch. For more information about structural directive, Please visit angular.io

Where can I find more articles in Angular2 series?

For learning Angular2, I think you should follow the list of articles as below (click on link to see detail page):

  • Overview: Introduce about Angular2
  • Routing: Understand how Angular2 navigate between pages/ components
  • Component: Learn about components/ pages in Angular2.
  • Binding: Learn how Angular2 show data on UI and receive input data from user.
  • Directive: Learn how to create re-usable component/ control that can be re-used across the application.
  • Integrate together: using what we learn about Angular for building the sample demo. 
  • Append "angular 2" into current "Angular 1" application.

Thank for reading.

Note: Please rate and share to your friends if you think this is usefull article, I really appreciate


Comments (1) -

999734 701053Wonderful post, thanks so considerably for sharing. Do you happen to have an RSS feed I can subscribe to? 756806


Add comment