Click here to Skip to main content
15,867,594 members
Articles / All Topics

Angular2 - Directives - Part 2

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
5 Feb 2017Apache3 min read 8.4K   5  
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 soluti

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>
        <div class="form-group ">
            <label>Last Name</label>
            <input class="form-control " [(ngModel)]="user.lastName " name="last " />
        </div>
    </form>
</div>

and userDetail.ts:

import {Component, Input} from "@angular/core";
@Component({
    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.

How about other attribute of component as directive?

This work the same as component in angular.

 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>
        <div class="form-group ">
            <label>Last Name</label>
            <input class="form-control " [(ngModel)]="user.lastName " name="last " />
        </div>
    </form>
</div>

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?

Please have a look below for the list of other articles:

  • 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. 

Thank for reading.

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

 

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


Written By
Architect
Vietnam Vietnam
I have more than 8 years in web development for multiple types of applications (ERP, Education System, ...).
I usually organize training/ coaching on specified topic (such as: RESTful/ WebApi, Angular2, BEM, LESS, SASS, EF, NodeJs ....). Please contact me on Skype (tranthanhtu83) or email (contact@tranthanhtu.vn) if need.
For more information about me, Please visit http://www.tranthanhtu.vn/page/about-me

Comments and Discussions

 
-- There are no messages in this forum --