Angular 2 属性指令 vs 结构指令

Angular 2 的指令有以下三种:

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

组件

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, HostListener} from "@angular/core";

@Directive({  selector: ‘[exeBackground]‘})
export class BeautifulBackgroundDirective {  

    private _defaultColor = ‘yellow‘;  
    private el: HTMLElement;  
    
    @Input(‘exeBackground‘)  backgroundColor: string;  
    constructor(el: ElementRef) {    
        this.el = el.nativeElement;    
        this.setStyle(this._defaultColor);  
    }  @HostListener(‘click‘)  
    
    onClick() { 
        this.setStyle(this.backgroundColor || this._defaultColor);  
    }  
    
    private setStyle(color: string) { 
        this.el.style.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;
}

总结

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

时间: 2024-08-07 10:29:05

Angular 2 属性指令 vs 结构指令的相关文章

Angular中的内置指令和自定义指令

NG中的指令,到底是什么(what)? 为什么会有(why)?以及怎样使用(how)? What: 在NG中,指令扩展HTML功能,为 DOM 元素调用方法.定义行为绑定数据等. Why: 最大程度减少DOM操作,实现数据绑定,与业务逻辑进行交互. How: 指令主要分为两种:内置指令和自定义指令,通过下面的例子,简单记录一下如何去使用. 内置指令 在官方API文档上罗列了很多指令,内置指令可以分为:普通指令 和 事件指令,他们都是作用于HTML之上的,通过添加属性的方式来实现的.简单看一下一些

angular核心原理解析3:指令的执行过程

指令的执行过程分析. 我们知道指令的执行分两个阶段,一个是compile,一个是link. 我们可以在指令中自定义compile和link. 首先,我们来讲解如何自定义link函数 举个例子: <!doctype html> <html ng-app="myModule"> <head> </head> <body> <hello></hello> </body> <script sr

Angularjs 事件指令 input 相关指令 和样式指令 DOM 操作指令详解

Angularjs 事件指令 input 相关指令 和样式指令DOM 操作指令详解学习要点:1. AngularJs 事件指令2. input 相关指令3. 样式指令4. DOM 操作指令5. ngBind/ngBindHtml/ngBindTemplate 重点6. ng-init ng-mode ng-model-options ng-controler 1. Angularjs 事件指令自己研究:ng-click/dbclickng-mousedown/upng-mouseenter/le

ARM常用重要的寄存器及指令解释 和 指令英文全称

一.常用的寄存器 r0 -r3    临时变量  用于传递参数,传递返回指,当传递参数的参数大于4个时,用栈空间.即开辟sp fp:frame pointer  记录回溯sp ip: 很少用 ,临时存放sp sp:指向栈顶 lr:link register 用于跳转时记录返回地址 pc:记录cpu运行指令的地址     因为arm采用流水线方式   取值  译码  执行等   pc=pc+8,     即pc指向当前执行的指令的下两条. cpsr :状态寄存器,每种工作模式有自己的cpsr,记录

Atitit..net&#160;clr&#160;il指令集&#160;以及指令分类&#160;&#160;与指令详细说明

Atitit..net clr il指令集 以及指令分类  与指令详细说明 1.1. .NET CLR 和 Java VM 都是堆叠式虚拟机器(Stack-Based VM), 1 1.2. 查看工具ILDASM1 1.3. 此程式执行时,关键的记忆体有三种,分別是:1 1.4. Il指令集2 1.4.1. Mov指令3 1.4.2.  跳转指令集合6 1.4.3.  算术 逻辑 与移位指令8 1.4.4. 类型转换9 1.4.5. Other  and oo指令10 2. 参考12 1.1. 

Atitit.java&#160;虚拟机的构成&#160;与指令分类&#160;与&#160;指令集合&#160;以及字节码查看工具javjap

Atitit.java 虚拟机的构成 与指令分类 与 指令集合 以及字节码查看工具javjap 1.1. 虚拟机的构成 java虚拟机--处理器.堆栈.寄存器.指令系统. 1 1.2. 虚拟机执行过程1 1.3. 约有250个指令2 2. JVM指令助记符 分类2 2.1. 变量到操作数栈:2 2.2. 算数指令3 2.3. 移位指令3 2.4. 逻辑指令4 2.5. 流程跳转指令4 2.6. Oo指令4 2.7. 运算指令 5 3. 查看指令反编译工具6 3.1.   分析java语言特性的一

3--jsp编译指令和动作指令

1.三个编译指令 1.1page指令(针对当前页面的指令)常用属性 (1)language:声明当前jsp程序的脚本语言的种类,默认是java (2)contentType:设置mime类型,设置生成网页的编码(text/html表明发送给浏览器的是网页数据) (3)charset:指定服务器生成网页的编码 (4)pageEncoding:设置jsp程序本身的编码 (5)import:倒入java类 (6)errorPage:表示如果发生异常错误时,网页会被重新指向指定的URL (7)isErr

JSP编译指令--------page编译指令

一.JSP编译指令 编译指令是通知JSP引擎的消息. 它的作用是设置JSP程序的属性以及由该JSP生成的Servlet的属性.比如指定JSP程序所使用的脚本语言.文件编码等等. 它不直接生成输出. 编译指令都有默认值,开发人员无需为每个指令设置值. JSP常用的编译指令有三个:page.include.tablib 1. page编译指令 page编译指令主要用于定义当前JSP程序的全局属性. 包括当前JSP程序所使用的脚本语言类型.需要导入的Java包的列表等等. 一般情况下,page编译指令

五、案例-指令参考-freemarker指令、表达式

案例-指令参考描述:本人自己测试写了一遍,如有错的地方,懂freemarker的朋友望指点指点! 案例-指令参考 表达式 一. Assign 1.<#assign name1="北京" name2="上海" name3="广东"> 调用:${name1}.${name2}.${name3} 2.<#assign name1> 消息模拟.. </#assign> 调用:${name1} 3.<#assign