Angular 2 属性指令 vs 结构指令
admin
2023-07-31 13:44:06
0

Angular 2 的指令有以下三种:

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

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

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

组件

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

@Component({  
    selector: 'my-app', // 定义组件在HTML代码中匹配的标签  
    template: `

Hello `name`

`,  // 指定组件关联的内联模板 }) export class AppComponent  {  name = 'Angular'; }

Angular 2 内置属性指令

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

使用常量

使用变量

具体示例:

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

@Component({
    selector: 'ngstyle-example',
    template: `
        
NgStyle
                                       {{ person.name }} (`person`.`country`)                       `}) 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.] 的语法:

      
     
         {{ person.name }} (`person`.`country`)
     

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

使用常量

使用变量

具体示例:

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

@Component({
    selector: 'ngclass-example',
    template: `
        
        
NgClass
                                      {{ person.name }} (`person`.`country`)                      `, }) export class NgClassExampleComponent {         people: any[] = [         { name: "Semlinker", country: 'CN' },         { name: "Donald John Trump", country: 'USA' },         { name: "Daniel Manson", country: 'UK' }         ]; }

Angular 2 内置结构指令

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


    {{ person.name }} (`person`.`country`)

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

`person`.`name`

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

  
    
        {{ person.name }} (`person`.`country`)  
      
    
        {{ person.name }} (`person`.`country`)
     
    
        {{ person.name }} (`person`.`country`)
    

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

2.ngFor指令:

   
    
 {{ person.name }} (`person`.`country`) 

3.ngSwitch指令:

  
    
       
         {{ person.name }} (`person`.`country`)
      
    
    
        
         {{ person.name }} (`person`.`country`)
         
      
     
        
         {{ person.name }} (`person`.`country`)
        
    

Angular 2 内置结构指令定义

1.ngIf指令定义:

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

2.ngFor指令定义:

@Directive({selector: '[ngFor][ngForOf]'})
export class NgForOf 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: `Hello `name``,
})
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,     
        private viewContainer: ViewContainerRef) {  }
}

2.指令应用

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

@Component({ 
    selector: 'my-app',  
    template: `Hello `name``, 
})
export class AppComponent  {  
    name = 'Angular';   
    condition: boolean = false;
}

总结

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


相关内容

热门资讯

瀚云通取得运动型线缆保护拖链专... 国家知识产权局信息显示,深圳市瀚云通科技有限公司取得一项名为“一种运动型线缆的保护拖链”的专利,授权...
第六届成渝双城青少年科技雏鹰研... 人民网重庆7月7日电 (记者胡虹)7月6日,由重庆市科协和成都市科协联合主办的第六届成渝双城青少年科...
三星Galaxy F70 Pr... IT之家 7 月 7 日消息,消息源 Mohammed Khatri 发文,透露三星旗下一款 Gal...
央媒关注!成都太空算力加速布局 7月6日,经济日报发布文章《太空算力加速布局》,其中关注成都构建从卫星制造到算力服务的全链条产业体系...
投资中国,与未来共舞——202... 7月8日下午,一场汇聚顶级资本力量与硬核科技创新力量的盛会——2026新京报贝壳财经年会未来大会 “...
美国恢复对伊朗石油制裁 根据美国财政部外国资产控制办公室当地时间7月7日消息,美国撤销一项授权允许伊朗石油销售的通用许可,相...
暗示要对梅洛尼下达限制令后,特... 当地时间7月7日,正在土耳其参加北约峰会的美国总统特朗普称意大利总理梅洛尼是“好人”,尽管他上周末曾...
广西近4000名被困师生欢呼:... 解放军来了!广西贵港高级中学近4000名师生被困,下午1点26分,解放军冲锋舟全速挺进救援现场,带着...
埃尔多安举行欢迎仪式,特朗普罕... 美国总统特朗普7月7日抵达土耳其首都安卡拉,参加即将在这里举行的北约峰会。当天,在土耳其总统埃尔多安...
纪念高善文:那个敢说真话、爱自... 对于无数投资者而言,高善文不仅是一位经济学家,更是中国证券研究行业从起步到成熟的见证者与塑造者。作者...