[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嵌入,这点之后的笔记会再详细 ...
随机推荐
- Linux系统性能监控
系统的性能指标主要包括CPU.内存.磁盘I/O.网络几个方面. 1. CPU性能 (1)利用vmstat命令监控系统CPU 该命令可以显示关于系统各种资源之间相关性能的简要信息,这里我们主要用它来看C ...
- 【转】错误日志ID8021来源BROWSER导致电脑死机
现场工控机死机,网上查了篇文章,具体原因还有待分析,下面是图 在这里有必要介绍两个ID号:6006和6005.在事件查看器里ID号为6006的事件表示事件日志服务已停止,如果你没有在当天的事件查看器中 ...
- 35、Android 性能优化、内存优化
http://blog.csdn.net/a_asinceo/article/details/8222104 http://blog.csdn.net/a_asinceo/article/detail ...
- UINavigationController 操作记录
//设置字体大小 颜色 { UIColor *color = [UIColor brownColor]; UIFont * font = [UIFont systemFontOfSize:20]; N ...
- 《转》DNS放大攻击
原文链接:http://blog.sina.com.cn/s/blog_90bb1f200101iazl.html 放大攻击(也称为杠杆攻击,英文名字DNS Amplification Attack) ...
- Unity3d 基于物理渲染Physically-Based Rendering之specular BRDF
在实时渲染中Physically-Based Rendering(PBR)中文为基于物理的渲染它能为渲染的物体带来更真实的效果,而且能量守恒 稍微解释一下字母的意思,为对后文的理解有帮助,从右到左L为 ...
- 一个使用微软Azure blob实现文件下载功能的实例-附带源文件
Running the sample Please follow the steps below. Step 1: Open the CSAzureServeFilesFromBlobStorage. ...
- 配置RHadoop与运行WordCount例子
1.安装R语言环境 su -c 'rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch. ...
- SQL Server 中的三种分页方式
USE tempdb GO SET NOCOUNT ON --创建表结构 IF OBJECT_ID(N'ClassB', N'U') IS NOT NULL DROP TABLE ClassB GO ...
- java的math常用方法
鉴于java求整时欲生欲死,整理常用math如下: 1: java取整 a:floor向下取整 用法:Math.floor(num) Math.floor(1.9)//1 ...