Angular 4 指令快速入门教程


Posted in Javascript onJune 07, 2017

本系列教程的开发环境及开发语言:

  1. Angular 4 +
  2. Angular CLI
  3. TypeScript

基础知识

Angular CLI 基本使用

安装 Angular CLI (可选)

npm install -g @angular/cli

创建新的项目

ng new PROJECT-NAME

启动本地服务器

cd PROJECT-NAME
ng serve

Angular 指令简介

Angular 的指令分为三种:

  1. 组件(Component directive):用于构建UI组件,继承于 Directive 类
  2. 属性指令(Attribute directive):用于改变组件的外观或行为
  3. 结构指令(Structural directive):用于动态添加或删除 DOM 元素来改变 DOM 布局

Angular 指令分类图

Angular 4 指令快速入门教程

Angular 组件组成图

Angular 4 指令快速入门教程

第一节 - 创建指令

在 Angular 中,我们可以使用 HostBinding 装饰器,实现元素的属性绑定。

指令的作用

该指令用于演示如何利用 HostBinding 装饰器,设置元素的 innerText 属性。

指令的实现

import { Directive, HostBinding} from '@angular/core';

@Directive({
  selector: '[greet]'
})
export class GreetDirective {
 @HostBinding() innerText = 'Hello, Everyone!';
}
指令的应用
import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
  <h2>Hello, Angular</h2>
  <h2 greet>Hello, Angular</h2>
 `,
})
export class AppComponent { }

第二节 - 定义输入属性

为了能够让用户自定义 GreetDirective 指令的问候内容,我们需要使用 Input 装饰器去定义指令的输入属性。

指令的作用

该指令用于演示如何利用 Input 装饰器,定义指令的输入属性,从而实现让用户自定义问候内容。

指令的实现

import { Directive, HostBinding, Input } from '@angular/core';

@Directive({
  selector: '[greet]'
})
export class GreetDirective {
  @Input() greet: string;
  @HostBinding() get innerText() {
    return this.greet;
  }
}

指令的应用

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
  <h2>Hello, Angular</h2>
  <h2 [greet]="'Hello, Semlinker!'">Hello, Angular</h2>
 `,
})
export class AppComponent { }

第三节 - 事件处理

在 Angular 中,我们可以使用 HostListener 属性装饰器,实现元素的事件绑定。

指令的作用

该指令用于演示如何利用 HostListener 装饰器,监听用户的点击事件。

指令的实现

import { Directive, HostBinding, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[greet]'
})
export class GreetDirective {
  @Input() greet: string;

  @HostBinding() get innerText() {
   return this.greet;
  }

  @HostListener('click',['$event']) 
  onClick(event) {
   this.greet = 'Clicked!';
  }
}

指令的应用

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
  <h2>Hello, Angular</h2>
  <h2 [greet]="'Hello, Semlinker!'">Hello, Angular</h2>
 `,
})
export class AppComponent { }

第四节 - 获取宿主元素属性值

在 Angular 中,我们可以通过 Attribute 装饰器来获取指令宿主元素的属性值。

指令的作用

该指令用于演示如何利用 Attribute 装饰器,获取指令宿主元素上的自定义属性 author 的值。

指令的实现

import { Directive, HostBinding, HostListener, Input, Attribute } from '@angular/core';

@Directive({
  selector: '[greet]'
})
export class GreetDirective {
  @Input() greet: string;

  @HostBinding() get innerText() {
    return this.greet;
  }

  @HostListener('click',['$event']) 
  onClick(event) {
    this.greet = 'Clicked!';
    console.dir(event);
  }

  constructor(@Attribute('author') public author: string) {
    console.log(author);
  }
}

指令的应用

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
  <h2>Hello, Angular</h2>
  <h2 [greet]="'Hello, Semlinker!'" 
   author="semlinker">Hello, Angular</h2>
 `,
})
export class AppComponent { }

第五节 - 使用 <ng-template> 元素

在 Angular 中,我们可以通过 ViewChild 装饰器来获取视图中定义的模板元素,然后利用 ViewContainerRef 对象的 createEmbeddedView() 方法,创建内嵌视图。

import { Component, TemplateRef, ViewContainerRef, ViewChild, 
 AfterViewInit } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
  <ng-template #tpl>
   Hello, Semlinker!
  </ng-template>
 `,
})
export class AppComponent implements AfterViewInit{
 @ViewChild('tpl')
 tplRef: TemplateRef<any>;

 constructor(private vcRef: ViewContainerRef) {}

 ngAfterViewInit() {
  this.vcRef.createEmbeddedView(this.tplRef);
 }
}

第六节 - 使用 ngTemplateOutlet 指令

ngTemplateOutlet 的作用

该指令用于基于已有的 TemplateRef 对象,插入对应的内嵌视图。在应用 NgTemplateOutlet 指令时,我们可以通过 [ngTemplateOutletContext] 属性来设置 EmbeddedViewRef 的上下文对象。绑定的上下文应该是一个对象,此外可通过 let语法来声明绑定上下文对象属性名。

ngTemplateOutlet 的使用

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
  <ng-template #stpl>
   Hello, Semlinker!
  </ng-template>
  <ng-template #atpl>
   Hello, Angular!
  </ng-template>
  <div [ngTemplateOutlet]="atpl"></div>
  <div [ngTemplateOutlet]="stpl"></div>
 `,
})
export class AppComponent { }

ngOutletContext 的使用

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
  <ng-template #stpl let-message="message">
   <p>{{message}}</p>
  </ng-template>
  <ng-template #atpl let-msg="message">
   <p>{{msg}}</p>
  </ng-template>
  <ng-template #otpl let-msg>
   <p>{{msg}}</p>
  </ng-template>
  <div [ngTemplateOutlet]="atpl"
   [ngOutletContext]="context">
  </div>
  <div [ngTemplateOutlet]="stpl"
   [ngOutletContext]="context">
  </div>
  <div [ngTemplateOutlet]="otpl"
   [ngOutletContext]="context">
  </div>
 `,
})
export class AppComponent {
 context = { message: 'Hello ngOutletContext!', 
  $implicit: 'Hello, Semlinker!' };
}

第七节 - 创建结构指令

指令的功能

该指令实现 ngIf 指令相反的效果,当指令的输入条件为 Falsy 值时,显示DOM元素。

指令的实现

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[exeUnless]'
})
export class UnlessDirective {

  @Input('exeUnless')
  set condition(newCondition: boolean) {
    if (!newCondition) { 
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

  constructor(private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef) {
  }
}

指令的应用

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
  <h2 *exeUnless="condition">Hello, Semlinker!</h2> 
 `,
})
export class AppComponent {
 condition: boolean = false;
}

我有话说

Angular 中指令与组件有什么关系?

组件继承于指令,并扩展了与 UI 视图相关的属性,如 template、styles、animations、encapsulation 等。

结构指令中的 TemplateRef 与 ViewContainerRef 有什么作用?

TemplateRef:用于表示内嵌的 template 模板元素,通过 TemplateRef 实例,我们可以方便创建内嵌视图(Embedded Views),且可以轻松地访问到通过 ElementRef 封装后的 nativeElement。需要注意的是组件视图中的 template 模板元素,经过渲染后会被替换成 comment 元素。

ViewContainerRef:用于表示一个视图容器,可添加一个或多个视图。通ViewContainerRef 实例,我们可以基于 TemplateRef 实例创建内嵌视图,并能指定内嵌视图的插入位置,也可以方便对视图容器中已有的视图进行管理。简而言之,ViewContainerRef 的主要作用是创建和管理内嵌视图或组件视图。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
javascript 解决表单仍然提交即使监听处理函数返回false
Mar 14 Javascript
jQuery fadeTo方法调整图片的透明度使用介绍
May 06 Javascript
jquery实现图片裁剪思路及实现
Aug 16 Javascript
JavaScript禁止页面操作的示例代码
Dec 17 Javascript
jquery easyui如何实现格式化列
Jul 30 jQuery
vue仿淘宝订单状态的tab切换效果
Jun 23 Javascript
mui back 返回刷新页面的实例
Dec 06 Javascript
Vue源码中要const _toStr = Object.prototype.toString的原因分析
Dec 09 Javascript
Node.js系列之安装配置与基本使用(1)
Aug 30 Javascript
关于layui 弹出层一闪而过就消失的解决方法
Sep 09 Javascript
Angular value与ngValue区别详解
Nov 27 Javascript
vue+node 实现视频在线播放的实例代码
Oct 19 Javascript
jstree单选功能的实现方法
Jun 07 #Javascript
JQueryMiniUI按照时间进行查询的实现方法
Jun 07 #jQuery
webpack打包单页面如何引用的js
Jun 07 #Javascript
vue使用Axios做ajax请求详解
Jun 07 #Javascript
Bootstrap fileinput文件上传组件使用详解
Jun 06 #Javascript
关于vue.js v-bind 的一些理解和思考
Jun 06 #Javascript
详解vue-cli开发环境跨域问题解决方案
Jun 06 #Javascript
You might like
thinkphp路由规则使用示例详解和伪静态功能实现(apache重写)
2014/02/24 PHP
延时重复执行函数 lLoopRun.js
2007/05/08 Javascript
JavaScript动态操作表格实例(添加,删除行,列及单元格)
2013/11/25 Javascript
使用jQuery判断IE浏览器版本的代码
2014/06/14 Javascript
使用原生JS实现弹出层特效
2014/12/22 Javascript
很全面的JavaScript常用功能汇总集合
2016/01/22 Javascript
jquery插件autocomplete用法示例
2016/07/01 Javascript
基于js中this和event 的区别(详解)
2017/10/24 Javascript
vue 组件中slot插口的具体用法
2018/04/03 Javascript
基于Node的Axure文件在线预览的实现代码
2019/08/28 Javascript
在Vue项目中,防止页面被缩放和放大示例
2019/10/28 Javascript
JS前端基于canvas给图片添加水印
2020/11/11 Javascript
Node快速切换版本、版本回退(降级)、版本更新(升级)
2021/01/07 Javascript
用Python和MD5实现网站挂马检测程序
2014/03/13 Python
Python多进程通信Queue、Pipe、Value、Array实例
2014/11/21 Python
Django中Forms的使用代码解析
2018/02/10 Python
windows下python安装pip图文教程
2018/05/25 Python
Python访问MongoDB,并且转换成Dataframe的方法
2018/10/15 Python
Python代码使用 Pyftpdlib实现FTP服务器功能
2019/07/22 Python
Pandas实现dataframe和np.array的相互转换
2019/11/30 Python
python对Excel的读取的示例代码
2020/02/14 Python
pyecharts调整图例与各板块的位置间距实例
2020/05/16 Python
python绘制汉诺塔
2021/03/01 Python
FOREO官方网站:LUNA露娜洁面仪
2016/11/28 全球购物
新西兰廉价汽车租赁:Snap Rentals
2018/09/14 全球购物
纽约海:Sea New York
2018/11/04 全球购物
打架检讨书300字
2014/02/02 职场文书
《夏夜多美》教学反思
2014/02/17 职场文书
服装设计专业自荐信
2014/06/17 职场文书
学习《中小学教师职业道德规范》心得体会
2016/01/18 职场文书
教育教学工作反思
2016/02/24 职场文书
乡镇团代会开幕词
2016/03/04 职场文书
用python画城市轮播地图
2021/05/28 Python
html form表单基础入门案例讲解
2021/07/21 HTML / CSS
mysql insert 存在即不插入语法说明
2022/03/25 MySQL
create-react-app开发常用配置教程
2022/06/25 Javascript