Angular 2 Directive

发布时间:2019-07-14 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Angular 2 Directive脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Angular 2 的指令分为以下三种:

  • 组件(component directive):用于构建UI组件,继承于 Directive 类

  • 属性指令(Attribute directive): 用于改变组件的外观或行为

  • 结构指令(Structural directive): 用于动态添加或删除DOM元素来改变DOM布局

图片描述

Angular 2 组件

图片描述

组件示例:

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

@Component({
  selector: 'my-app', // 定义组件在HTML代码中匹配的标签
  template: `<h1>Hello {{name}}</h1>`, // 指定组件关联的内联模板
})
export class AppComponent  {
  name = 'Angular'; 
}

Angular 2 内置属性指令

1.ngStyle指令: 用于设定给定 DOM 元素的 style 属性

绑定常量

<div [ngStyle]="{'background-color': 'green'}"></div>

绑定表达式

<div [ngStyle]="{'background-color': person.country === 'UK' ? 'green' : 'red'}">

具体示例:

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

@Component({
    selector: 'ngstyle-example',
    template: `<h4>NgStyle</h4>
    <ul *ngFor="let person of people">
        <li [ngStyle]="{'color': getColor(person.country)}">
            {{ person.name }} ({{person.country}})
        </li>
    </ul>
    `
})
export class NgStyleExampleComponent {

    getColor(country: string) {
        switch (country) {
            case 'CN':
                return 'red';
            case 'USA':
                return 'blue';
            case 'UK':
                return 'green';
        }
    }

    people: any[] = [
        {
            name: "Semlinker",
            country: 'CN'
        },
        {
            name: "Donald John Trump",
            country: 'USA'
        },
        {
            name: "Daniel Manson",
            country: 'UK'
        }
    ];
}

上面的例子,除了使用 ngStyle 指令,我们还可以使用 [style.<PRoperty>] 的语法:

 <ul *ngFor="let person of people">
     <li [style.color]="getColor(person.country)">
        {{ person.name }} ({{person.country}})
     </li>
</ul>

2.ngClass指令:用于动态的设定 DOM 元素的 CSS class

绑定常量

<div [ngClass]="{'text-success': true }"></div>

绑定表达式

<div [ngClass]="{'text-success': person.country === 'CN'}"></div>

具体示例:

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

@Component({
    selector: 'ngclass-example',
    template: `
    <style>
      .text-success {
         color: green 
      }
      .text-primary {
          color: red
      }
      .text-secondary {
          color: blue
      } 
    </style>
    <h4>NgClass</h4>
    <ul *ngFor="let person of people">
        <li [ngClass]="{
           'text-success': person.country === 'UK',
           'text-primary': person.country === 'CN',
           'text-secondary': person.country === 'USA'  
          }"> {{ person.name }} ({{person.country}})
        </li>
    </ul>
    `,
   
})
export class NgClassExampleComponent {

    people: any[] = [
        {
            name: "Semlinker",
            country: 'CN'
        },
        {
            name: "Donald John Trump",
            country: 'USA'
        },
        {
            name: "Daniel Manson",
            country: 'UK'
        }
    ];
}

Angular 2 内置结构指令

1.ngIf指令:根据表达式的值,显示或移除元素

<div *ngIf="person.country === 'CN'">{{ person.name }} ({{person.country}})</div>

2.ngFor指令:使用可迭代的每个项作为模板的上下文来重复模板,类似于 Ng 1.x 中的 ng-repeat 指令

<div *ngFor="let person of people">{{person.name}}</div>

3.ngSwitch指令:它包括两个指令,一个属性指令和一个结构指令。它类似于 JavaScript 中的 switch 语句

<ul [ngSwitch]='person.country'>
  <li *ngSwitchCase="'UK'" class='text-success'>
      {{ person.name }} ({{person.country}})
  </li>
   <li *ngSwitchCase="'USA'" class='text-secondary'>
      {{ person.name }} ({{person.country}})
  </li>
  <li *ngSwitchDefault class='text-primary'>
    {{ person.name }} ({{person.country}})
  </li>
</ul>

通过上面的例子,可以看出结构指令和属性指令的区别。结构指令是以 * 作为前缀,这个星号其实是一个语法糖。它是 ngIfngFor 语法的一种简写形式。Angular 引擎在解析时会自动转换成 <template> 标准语法。

Angular 2 内置结构指令标准形式

1.ngIf指令:

<template [ngIf]='condition'>
   <p>I am the content to show</p>
</template>

2.ngFor指令:

<template ngFor [ngForOf]="people" let-person>
   <div> {{ person.name }} ({{person.country}}) </div>
</template>

3.ngSwitch指令:

<ul [ngSwitch]='person.country'>
  <template [ngSwitchCase]="'UK'">
      <li class='text-success'>
          {{ person.name }} ({{person.country}})
        </li>
  </template>
  <template [ngSwitchCase]="'USA'">
      <li class='text-secondary'>
          {{ person.name }} ({{person.country}})
        </li>
  </template>
  <template [ngSwitchDefault]>
      <li class='text-primary'>
          {{ person.name }} ({{person.country}})
        </li>
  </template>
</ul>

Angular 2 内置结构指令定义

1.ngIf指令定义:

@Directive({selector: '[ngIf]'})
export class NgIf {}

2.ngFor指令定义:

@Directive({selector: '[ngFor][ngForOf]'})
export class NgForOf<T> implements DoCheck, OnChanges {}

3.ngSwitch指令定义:

@Directive({selector: '[ngSwitch]'})
export class NgSwitch {}

@Directive({selector: '[ngSwitchCase]'})
export class NgSwitchCase implements DoCheck {}

@Directive({selector: '[ngSwitchDefault]'})
export class NgSwitchDefault {}

自定义属性指令

指令功能描述:该指令用于在用户点击宿主元素时,根据输入的背景颜色,更新宿主元素的背景颜色。宿主元素的默认颜色是黄色。

1.指令实现

import {Directive, Input, ElementRef, Renderer, HostListener} from "@angular/core";

@Directive({
  selector: '[exeBackground]'
})
export class ExeBackgroundDirective {
  private _defaultColor = 'yellow';

  @Input('exeBackground')
  backgroundColor: string; // 输入属性,用于设置元素的背景颜色

  constructor(private elementRef: ElementRef, private renderer: Renderer) {
    this.setStyle(this._defaultColor);
  }

  @HostListener('click')
  onClick() { // 监听宿主元素的点击事件,设置元素背景色
    this.setStyle(this.backgroundColor || this._defaultColor);
  }

  private setStyle(color: string) { // 调用renderer对象提供的API设置元素的背景颜色
    this.renderer.setElementStyle(this.elementRef.nativeElement, 
      'backgroundColor', color);
  }
}

2.指令应用:

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

@Component({
  selector: 'my-app', 
  template: `<h1 [exeBackground]="'red'">Hello {{name}}</h1>`,
})
export class AppComponent  {
  name = 'Angular'; 
}

自定义结构指令

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

1.指令实现

@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) {
  }
}

2.指令应用

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

@Component({
  selector: 'my-app',
  template: `<h1 [exeBackground]="'red'" *exeUnless="condition">Hello {{name}}</h1>`, 
})
export class AppComponent  {
  name = 'Angular'; 
  condition: boolean = false;
}

我有话说

1.自定义属性指令中的 ElementRefRenderer 的作用

为了能够支持跨平台,Angular 2 通过抽象层封装了不同平台的差异,统一了 API 接口。如定义了抽象类 Renderer 、抽象类 RootRenderer 等。此外还定义了以下引用类型:ElementRef、TemplateRef、ViewRef 、ComponentRef 和 ViewContainerRef 等。

详细内容请参考 - Angular 2 ElementRef

2.自定义结构指令中的 TemplateRefViewContainerRef 的作用

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

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

详细内容请参考 - Angular 2 TemplateRef & ViewContainerRef

3.Angular 2 中指令与组件的关系

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

详细内容请参考 - Angular 2 Directive Lifecycle

图片描述

总结

本文主要介绍了 Angular 2 中的指令,通过具体示例介绍了 Angular 2 常见内建指令的使用方式和区别。最终,我们通过自定义属性指令和自定义结构指令两个示例,展示了如何开发自定义指令。

脚本宝典总结

以上是脚本宝典为你收集整理的Angular 2 Directive全部内容,希望文章能够帮你解决Angular 2 Directive所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。