First, What is directive, what is the difference between component and directive.

For my understanding,

  • component is something like 'canvas', 'form', 'table'... they have the template and their own functionality. It defines how a html tag should work like and look like.
  • directive is something like 'ngIf', 'required', 'checked'... they don't necessary to have their own template (of course they can have). It change the original component way to work or looks like.

Basic 'directive' and 'component' they are quite similar, so just follow the rules when you want to choose using 'directive' or 'component':

  1. Add something new to the DOM with its own template, using component
  2. Modify something (can be functionality or template) already in teh DOM, using directive.

What we want to build is collapse directive:

When you double click the panel, it will toggle the content show / hide and change the icon.

Also when you click the button which outside the panel, you will also be able to toggle the panel.

So it requires you know

  • How to deal with Host elm's events --> @HostListener
  • How to deal with Host elm's attrs --> @HostBinding
  • How to export directive as API for the component which stay outside the host elm to use --> exportAs

First. let's see how to toggle it by using @HostListener & @HostBinding:

the host element html:

        <div collapse-on-click
class="card card-strong disable-text-selection">
<i class="md-icon collapsible-indicator" >arrow_drop_down</i>
<i class="md-icon collapsible-indicator" >arrow_drop_up</i> <div class="collapsible-section" >
This page section is collapsible, double click it and it will collapse or expand.
</div>
</div>

css:

.collapsed .collapsible-section{
display: none;
}

directive:

import {Directive, HostListener, HostBinding} from "@angular/core";
@Directive({
selector: '[collapse-on-click]'
})
export class CollapseOnClick { collapsed:boolean;
constructor(){
this.collapsed = false;
} // set "collapsed" class to the host element according to
// this.collapsed value
@HostBinding('class.collapsed')
get isCollapsed(){
return this.collapsed;
} // if the double click the host element, will fire toggle function
@HostListener('dblclick')
toggle(){
this.collapsed = !this.collapsed;
}
}

So everytime, when you double click the host element, it will run 'toggle()' function, it will change 'this.collapsed' value to true or false. Then we have a getter and setter to get and set 'this.collapsed'. According to 'this.collapsed', we will add 'collapsed' class to host element. This class will help to hide the content, as we define in css file.

So when toggle: true: the host html will change to:

<div collapse-on-click
class="card card-strong disable-text-selection collasped">

When toggle: false:

<div collapse-on-click
class="card card-strong disable-text-selection">

To switch the icon, we can use template reference from directive:

@Directive({
selector: '[collapse-on-click]',
exportAs: 'collapsible'
})

We define exportAs, which we can refer in host html:

        <div collapse-on-click #panel="collapsible"
class="card card-strong disable-text-selection">
<i class="md-icon collapsible-indicator" *ngIf="!panel.collapsed">arrow_drop_down</i>
<i class="md-icon collapsible-indicator" *ngIf="panel.collapsed">arrow_drop_up</i> <div class="collapsible-section" >
This page section is collapsible, double click it and it will collapse or expand.
</div>
</div>

And one improvement for using template reference is we not longer need to depend on a css class 'collapsed', to show / hide the content, we can just use ngIf.

        <div collapse-on-click #panel="collapsible"
class="card card-strong disable-text-selection">
<i class="md-icon collapsible-indicator" *ngIf="!panel.collapsed">arrow_drop_down</i>
<i class="md-icon collapsible-indicator" *ngIf="panel.collapsed">arrow_drop_up</i> <div class="collapsible-section" *ngIf="!panel.collapsed">
This page section is collapsible, double click it and it will collapse or expand.
</div>
</div>

This way can make the direcitve more reuseable.

Another benifite for using tempalte reference is that, we can call directive function or access directive props by ref.

        <div collapse-on-click #panel="collapsible"
class="card card-strong disable-text-selection">
<i class="md-icon collapsible-indicator" *ngIf="!panel.collapsed">arrow_drop_down</i>
<i class="md-icon collapsible-indicator" *ngIf="panel.collapsed">arrow_drop_up</i> <div class="collapsible-section" *ngIf="!panel.collapsed">
This page section is collapsible, double click it and it will collapse or expand.
</div>
</div>
<hr />
<button (click)="panel.toggle()">Toggle: {{panel.collapsed}}</button>

So, we add a button, which stay outside the host element. When it clicked, it will also call the toggle() method on directive to show / hide the content.

Notice: another way to write @HostListener:

@Directive({
selector: '[collapse-on-click]',
exportAs: 'collapsible',
host: {
'(dblclick)': 'toggle()'
}
})

It is also clear.

------------------

app.ts:

import {Component} from "@angular/core";
import {NgModule} from "@angular/core";
import {platformBrowserDynamic} from "@angular/platform-browser-dynamic";
import {BrowserModule} from "@angular/platform-browser"; import {CollapseOnClick} from "./collapse-on-click.directive"; @Component({
selector:'app',
template: ` <div collapse-on-click #panel="collapsible"
class="card card-strong disable-text-selection">
<i class="md-icon collapsible-indicator" *ngIf="!panel.collapsed">arrow_drop_down</i>
<i class="md-icon collapsible-indicator" *ngIf="panel.collapsed">arrow_drop_up</i> <div class="collapsible-section" *ngIf="!panel.collapsed">
This page section is collapsible, double click it and it will collapse or expand.
</div>
</div>
<hr />
<button (click)="panel.toggle()">Toggle: {{panel.collapsed}}</button>
`
})
export class App { } @NgModule({
declarations: [App, CollapseOnClick],
imports: [BrowserModule],
bootstrap: [App]
})
export class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule);

collapsed-on-click.ts:

import {Directive, HostListener, HostBinding} from "@angular/core";
@Directive({
selector: '[collapse-on-click]',
exportAs: 'collapsible'
})
export class CollapseOnClick { collapsed:boolean;
constructor(){
this.collapsed = false;
} // set "collapsed" class to the host element according to
// this.collapsed value
/*@HostBinding('class.collapsed')
get isCollapsed(){
return this.collapsed;
}*/ // if the double click the host element, will fire toggle function
@HostListener('dblclick')
toggle(){
this.collapsed = !this.collapsed;
}
}

[Angular 2] Directive intro and exportAs的更多相关文章

  1. [Angular] Export directive functionalities by using 'exportAs'

    Directive ables to change component behaives and lookings. Directive can also export some APIs which ...

  2. 关于angular 自定义directive

    关于angular 自定义directive的小结 首先我们创建一个名为"expander"的自定义directive指令: angular.module("myApp& ...

  3. [Angular] Custom directive Form validator

    Create a directive to check no special characters allowed: import {Directive, forwardRef} from '@ang ...

  4. [Angular] Test Directive

    directive: import { Directive, HostListener, HostBinding, ElementRef } from '@angular/core'; @Direct ...

  5. [Angular] Using directive to create a simple Credit card validator

    We will use 'HostListener' and 'HostBinding' to accomplish the task. The HTML: <label> Credit ...

  6. angular service/directive

    <html class=" js cssanimations csstransitions" ng-app="phonecatApp" > < ...

  7. 一个Demo就懂的Angular之directive

    <body> <div ng-controller="myCtrl"> <hello-word></hello-word> < ...

  8. angular 中 directive中的多个指令

    <div ng-controller="ctrl1"> <superman weight length speed>superman</superma ...

  9. Angular中directive——scope选项与绑定策略,这个也经常迷惑的。

    开门见山地说,scope:{}使指令与外界隔离开来,使其模板(template)处于non-inheriting(无继承)的状态,当然除非你在其中使用了transclude嵌入,这点之后的笔记会再详细 ...

随机推荐

  1. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

    #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)宏的运行机理:1. ( (TYPE *)0 ) 将零转型为TY ...

  2. ArcMap自定义脚本工具制作

    原文 ArcMap自定义脚本工具制作 在制图的前期,一般需要做一些数据的整理,如图层合并.裁剪等工作.虽然在ArcMap中也有提供对应的工具,但使用起来需要点技巧.如批量裁剪,虽然可以实现,但出来的结 ...

  3. UI篇--布局问题

    1.android:layout_marginRight 不起作用解决方法 今天想在RelativeLayout的左右分别放上一个按钮, 左边按钮用marginLeft="10dp" ...

  4. 两个数组a[N],b[N],其中A[N]的各个元素值已知,现给b[i]赋值,b[i] = a[0]*a[1]*a[2]…*a[N-1]/a[i];

    转自:http://blog.csdn.net/shandianling/article/details/8785269 问题描述:两个数组a[N],b[N],其中A[N]的各个元素值已知,现给b[i ...

  5. Python绘图和数值工具:matplotlib 和 numpy下载与使用

    安装任何python模块的标准方式是使用标准的python版本,然后添加标准的模块最简单的方法是登陆相应的网站下载程序包. 但是要考虑依赖关系 , 平台和Python版本号. windows一般带有安 ...

  6. Asp.net MVC 处理文件的上传下载

    如果你仅仅只有Asp.net Web Forms背景转而学习Asp.net MVC的,我想你的第一个经历或许是那些曾经让你的编程变得愉悦无比的服务端控件都驾鹤西去了.FileUpload就是其中一个, ...

  7. 【和我一起学python吧】Python安装、配置图文详解

     Python安装.配置图文详解 目录: 一. Python简介 二. 安装python 1. 在windows下安装 2. 在Linux下安装 三. 在windows下配置python集成开发环境( ...

  8. codeforces 704B - Ant Man 贪心

    codeforces 704B - Ant Man 贪心 题意:n个点,每个点有5个值,每次从一个点跳到另一个点,向左跳:abs(b.x-a.x)+a.ll+b.rr 向右跳:abs(b.x-a.x) ...

  9. [Hive - LanguageManual] Hive Default Authorization - Legacy Mode

    Disclaimer Prerequisites Users, Groups, and Roles Names of Users and Roles Creating/Dropping/Using R ...

  10. mvn deploy 报错:Return code is: 400, ReasonPhrase: Bad Request. ->

    mvn deploy 报错:Return code is: 400, ReasonPhrase: Bad Request. -> TEST通过没有报错,但是最终部署到Nexus中时出现错误. 后 ...