脚本宝典收集整理的这篇文章主要介绍了Angular--Directive,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
在Angular2中有三种类型的指令(Directive) ,如下:
1. 属性型指令 - 改变元素显示和行为的指令。例如:NgStyle …
2. 结构型指令 - 通过添加和移除DOM元素来改变DOM结构的指令。例如:NgFor, NgIf …
3. 组件 — 拥有模板的指令。
一、属性指令(ngStyle ,ngClass)
NgStyle
绑定一个有形如CSS属性名:value的对象,其中value为具体的css样式,eg:
<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:绑定到一个返回控制条件的值表达式
NgSwitchCase:绑定到一个返回匹配条件的值表达式
NgSwitchDefault:用于标记默认元素的属性,是可选的。如果我们不用它,那么当 myVar 没有匹配到任何期望的值
时就不会渲染任何东西。
使用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元素上,也就是我们需要为我们定一个这个指令找到一个宿主元素。
2、之后我们创建一个quotationArea.directive.tss文件,其代码结构如下:
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...
以上是脚本宝典为你收集整理的Angular--Directive全部内容,希望文章能够帮你解决Angular--Directive所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。