Angular--Directive
在Angular2中有三种类型的指令(Directive) ,如下: 一、属性指令(ngStyle ,ngClass) NgStyle <div [ngStyle]="{color: 'white','background-color':'green'}"></<div> 注意,在 ngStyle 的说明中,我们对 background-color 使用了单引号,但却没有对 color 使用。这是为什么呢?因为 ngStyle 的参数是一个JavaScript对象,而color 是一个合法的键,不需要引号。但是在 background-color 中,连字符是不允许出现在对象的键名当中的,除非它是一个字符串,因此使用了引号。通常情况下,尽量不会对对象的键使用引号,除非不得不用。 //动态使用 <span [ngStyle]="{color: color}">{{ color }} text</span> //判断添加 <div [ngStyle]="{'background-color':username === 'zxc' ? 'green' : 'red' }"></<div> NgClass //基本用法 <div [ngClass]="{bordered: false}">此时div不包含bordered 类名</div> <div [ngClass]="{bordered: true}">此时div含有bordered 类名</div> //判断 <i [ngClass]="{green: isAddr,red: !isAddr}"></i>
二、结构型指令(ngIf ,ngFor ,ngSwitch) NgIf 如果表达式的结果返回的是一个假值,那么元素会从DOM上被移除。 <div *ngIf="false"></div> //不显示 <div *ngIf="a > b"></div>// <div *ngIf="str == 'yes'"></div> <div *ngIf="myFunc()"></div> NgFor this.cities = ['厦门','福州','漳州']; <div class="ui list" *ngFor="let c of cities">{{ c }}</div> 获取索引 <div class="ui list" *ngFor="let c of cities; let num = index">{{ num+1 }} . {{ c }}</div> 结果如下: ngSwitch <div class="container"> <div *ngIf="myVar == 'A'">Var is A</div> <div *ngIf="myVar == 'B'">Var is B</div> <div *ngIf="myVar == 'C'">Var is C</div> <div *ngIf="myVar != 'A' && myVar != 'B' && myVar != 'C'">Var is something else</div> </div> 对于这种情况,Angular引入了 ngSwitch 指令。 NgSwitch:绑定到一个返回控制条件的值表达式 <div class="container" [ngSwitch]="myVar"> <div *ngSwitchCase="'A'">Var is A</div> <div *ngSwitchCase="'B'">Var is B</div> <div *ngSwitchCase="'C'">Var is C</div> <div *ngSwitchDefault>Var is something else</div> </div> 三、组件 属性型指令的创建至少需要一个带有@Directive装饰器修饰的控制器类。@Directive装饰器指定了一个选择器名称,用于指出与此指令相关联的属性的名字。 接下来,开始创建一个简单的属性型指令,该指令的功能是,user-quotation-view.component.html页面刷新时获取.quotation-area的最小高度。 1、首先我们确认好指令名字,quotationArea <div class="quotation-area" quotationArea></div> 把这个指令作为一个属性应用到一个DOM元素上,也就是我们需要为我们定一个这个指令找到一个宿主元素。 import {Component,Directive,ElementRef,OnInit} from '@angular/core'; @Directive({ selector: '[quotationArea]'}) export class QuotationAreaDirective implements OnInit { el:ElementRef; constructor(el: ElementRef) { this.el = el; } ngOnInit() { const $el = $(this.el.nativeElement); const windowHeight = document.documentElement.clientHeight; //获取窗口高度 const bar=document.getElementsByClassName('bar-nav')[0] const barHeight =bar.clientHeight; const heightValue=windowHeight - barHeight; $el.css('height',(heightValue) + 'px'); } } 3、接下来 我们需要在module.ts中来显示的声明我们自己定义的指令,以便Angualr在解析模板时,能够正确的识别我们自己定一个指令。 import {QuotationAreaDirective} from './user-quotation/user-quotation-view/quotationArea.directive'; declarations: [QuotationAreaDirective] 结果如图:
参考文章:https://blog.csdn.net/shenlei... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |