[Angular 2] Directive intro and exportAs
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':
- Add something new to the DOM with its own template, using component
- 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的更多相关文章
- [Angular] Export directive functionalities by using 'exportAs'
Directive ables to change component behaives and lookings. Directive can also export some APIs which ...
- 关于angular 自定义directive
关于angular 自定义directive的小结 首先我们创建一个名为"expander"的自定义directive指令: angular.module("myApp& ...
- [Angular] Custom directive Form validator
Create a directive to check no special characters allowed: import {Directive, forwardRef} from '@ang ...
- [Angular] Test Directive
directive: import { Directive, HostListener, HostBinding, ElementRef } from '@angular/core'; @Direct ...
- [Angular] Using directive to create a simple Credit card validator
We will use 'HostListener' and 'HostBinding' to accomplish the task. The HTML: <label> Credit ...
- angular service/directive
<html class=" js cssanimations csstransitions" ng-app="phonecatApp" > < ...
- 一个Demo就懂的Angular之directive
<body> <div ng-controller="myCtrl"> <hello-word></hello-word> < ...
- angular 中 directive中的多个指令
<div ng-controller="ctrl1"> <superman weight length speed>superman</superma ...
- Angular中directive——scope选项与绑定策略,这个也经常迷惑的。
开门见山地说,scope:{}使指令与外界隔离开来,使其模板(template)处于non-inheriting(无继承)的状态,当然除非你在其中使用了transclude嵌入,这点之后的笔记会再详细 ...
随机推荐
- Delphi的windows剪切板操作函数
1. Clipbrd函数 function Clipboard: TClipboard;:若应用程序从未使用过剪贴板,则调用该函数形成新的剪贴板:若之前使用过剪贴板则返回使用过的剪贴板. 属性: As ...
- Python中的高级数据结构
数据结构 数据结构的概念很好理解,就是用来将数据组织在一起的结构.换句话说,数据结构是用来存储一系列关联数据的东西.在Python中有四种内建的数据结构,分别是List.Tuple.Dictionar ...
- 当rsync遇到非默认端口的ssh
在使用rsync使用ssh协议,来同步远程文件的方法,rsync -zvrtopg -e ssh但是如果遇到ssh不是22端口的时候使用rsync -zvrtopg -e ‘ssh -p 端口’特别是 ...
- matlab图像基础知识
1.MATLAB支持的几种图像文件格式: ⑴JPEG(Joint Photogyaphic Expeyts Group):一种称为联合图像专家组的图像压缩格式. ⑵BMP(Windows Bitmap ...
- <Chapter 2>2-1.安装SDK
开发一个应用需要的所有工具都包含在App Engine SDK中.对于Java和Python有不同的SDKs,每个都有特性对于用那种语言开发是有益的.SDKs在任何平台上工作,包括Windows,Ma ...
- 二、python 函数
1.定义函数 def max(x,y): if x>y: return x else: return y 如果定义空函数(函数还没想好怎么编写,只是为了让整个代码能够运行起来) def max( ...
- HttpComponents 学习的两个重要文档
httpcore-tutorial-simplified-chinese httpclient-tutorial-simplified-chinese
- 将大数据利用 BCP 导出SqlServer数据到CSV
--导出数据 --BCP [数据库]..[数据库表] out "d:\abc.csv" -c -t "|" -T bcp "SELECT * FROM ...
- 使用paramiko进行打包操作
使用paramiko执行ssh命令的时候有一个很坑爹的地方:它无法准确的识别你的系统环境变量,所以使用一些命令的时候会发现,直接在系统中执行该命令的时候可以,但是换成paramiko执行的时候会报错说 ...
- jsp页面显示数据库的数据信息表
在日常jsp开发中:最基本的一个操作之一是把之前添加到数据库中的信息在jsp页面中显示出来,也就是增删改查中的查找的一部分: 下面是以上部分的开发步骤及分析. 1.在jsp页面: <thead& ...