Angular 4 指令快速入门教程

 更新时间:2017年06月07日 09:52:19   作者:semlinker  
本篇文章主要介绍了Angular 4 指令快速入门教程,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

  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 组件组成图

第一节 - 创建指令

在 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 的主要作用是创建和管理内嵌视图或组件视图。

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

相关文章

  • 浅谈angular.copy() 深拷贝

    浅谈angular.copy() 深拷贝

    本篇文章主要介绍了浅谈angular.copy() 深拷贝,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • AngularJs  Using $location详解及示例代码

    AngularJs Using $location详解及示例代码

    本文主要介绍AngularJs Using $location的知识资料,这里整理了相关的资料,及简单示例代码,有兴趣的小伙伴可以参考下
    2016-09-09
  • Angular 7工作方式事件绑定

    Angular 7工作方式事件绑定

    在本章中将讨论事件绑定在Angular7中的工作方式,当用户以键盘移动,鼠标单击或鼠标悬停的形式与应用程序交互时,它将生成一个事件,需要处理这些事件以执行某种操作,考虑一个示例以更好地理解这一点
    2023-12-12
  • AngularJS中$injector、$rootScope和$scope的概念和关联关系深入分析

    AngularJS中$injector、$rootScope和$scope的概念和关联关系深入分析

    这篇文章主要介绍了AngularJS中$injector、$rootScope和$scope的概念和关联关系,结合实例形式较为深入的分析了$injector、$rootScope和$scope的概念、功能、使用方法及相互之间的关系,需要的朋友可以参考下
    2017-01-01
  • Angular学习笔记之angular的$filter服务浅析

    Angular学习笔记之angular的$filter服务浅析

    本文是小编记录的angular学习笔记,通过本文首先给大家介绍了$filter服务,然后介绍下内置filter及filter的简单使用,非常不错具有参考借鉴价值,感兴趣的朋友一起看看吧
    2016-11-11
  • 详解Angular 4.x NgTemplateOutlet

    详解Angular 4.x NgTemplateOutlet

    这篇文章主要介绍了详解Angular 4.x NgTemplateOutlet,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • 在Angular中如何监听某个值的变化

    在Angular中如何监听某个值的变化

    这篇文章主要介绍了在Angular中如何监听某个值的变化问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Angular2平滑升级到Angular4的步骤详解

    Angular2平滑升级到Angular4的步骤详解

    最近Angular项目组终于发布了新版——正式版 Angular 4.0.0。所以想着就来尝试下升级,记录下整个升级过程分享给大家,所以这篇文章主要介绍了Angular2升级到Angular4的详细步骤,需要的朋友可以参考下。
    2017-03-03
  • angularjs创建弹出框实现拖动效果

    angularjs创建弹出框实现拖动效果

    这篇文章主要为大家详细介绍了angularjs创建弹出框实现拖动效果的相关资料,angularjs modal模态框创建可拖动的指令,感兴趣的小伙伴们可以参考一下
    2016-01-01
  • AngularJS基础 ng-init 指令简单示例

    AngularJS基础 ng-init 指令简单示例

    本文主要介绍AngularJS ng-init 指令,这里帮大家整理了关于ng-init 指令的基本知识资料,并附有简单的代码示例,有需要学习的小伙伴可以参考下
    2016-08-08

最新评论