Angular4之常用指令
Angular4指令
NgIf
<div *ngIf="false"></div> <!-- never displayed -->
<div *ngIf="a > b"></div> <!-- displayed if a is more than b -->
<div *ngIf="str == 'yes'"></div> <!-- displayed if str holds the string "yes" -->
<div *ngIf="myFunc()"></div> <!-- displayed if myFunc returns a true value -->
NgSwitch
有时候需要根据不同的条件,渲染不同的元素,此时我们可以使用多个ngIf来实现。
<div class="container">
<div *ngIf="myVar == 'A'">Var is A</div>
<div *ngIf="myVar == 'B'">Var is B</div>
<div *ngIf="myVar != 'A' && myVar != 'B'">Var is something else</div>
</div>
如果myVar的可选值多了一个'C',就得相应增加判断逻辑:
<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>
可以发现 Var is something else 的判断逻辑,会随着 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>
NgStyle
NgStyle让我们可以方便的通过Angular表达式,设置DOM元素的css属性。
- 设置元素的背景颜色
<div [style.background-color="'yellow'"]>
Use fixed yellow background
</div>
- 设置元素的字体大小
<!-- 支持单位: px | em | %-->
<div>
<span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize">
red text
</span>
</div>
NgStyle支持通过键值对的形式设置DOM元素的样式:
<div [ngStyle]="{color: 'white', 'background-color': 'blue'}">
Uses fixed white text on blue background
</div>
注意到 background-color 需要使用单引号,而 color 不需要。这其中的原因是,ng-style 要求的参数是一个 Javascript 对象,color 是一个有效的 key,而 background-color 不是一个有效的 key ,所以需要添加 ''。
@Directive({selector: '[ngStyle]'})
export class NgStyle implements DoCheck {
private _ngStyle: {[key: string]: string};
private _differ: KeyValueDiffer<string, string|number>;
constructor(
private _differs: KeyValueDiffers,
private _ngEl: ElementRef,
private _renderer: Renderer) {}
@Input()
set ngStyle(v: {[key: string]: string}) {
// <div [ngStyle]="{color: 'white', 'background-color': 'blue'}">
this._ngStyle = v;
if (!this._differ && v) {
this._differ = this._differs.find(v).create();
}
}
// 设置元素的样式
private _setStyle(nameAndUnit: string, value: string|number): void {
const [name, unit] = nameAndUnit.split('.'); // 截取样式名和单位
value = value != null && unit ? `${value}${unit}` : value;
this._renderer.setElementStyle(this._ngEl.nativeElement, name, value as string);
}
}
NgClass
NgClass接收一个对象字面量,对象的key是CSS class的名称,value的值是truthy/falsy的值,表示是否应用该样式。
- CSS Class
.bordered {
border: 1px dashed black; background-color: #eee;
}
- HTML
<!-- Use boolean value -->
<div [ngClass]="{bordered: false}">This is never bordered</div>
<div [ngClass]="{bordered: true}">This is always bordered</div>
<!-- Use component instance property -->
<div [ngClass]="{bordered: isBordered}">
Using object literal. Border {{ isBordered ? "ON" : "OFF" }}
</div>
<!-- Class names contains dashes -->
<div[ngClass]="{'bordered-box': false}">
Class names contains dashes must use single quote
</div>
<!-- Use a list of class names -->
<div class="base" [ngClass]="['blue', 'round']">
This will always have a blue background and round corners
</div>
NgFor
NgFor指令用来根据集合(数组),创建DOM元素,类似于ng1中的ng-repeat指令
<div class="ui list" *ngFor="let c of cities; let num = index">
<div class="item">{{ num+1 }} - {{ c }}</div>
</div>
使用trackBy提高列表的性能
@Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li>
</ul>
<button (click)="getItems()">Refresh items</button>
`,
})
export class App {
constructor() {
this.collection = [{id: 1}, {id: 2}, {id: 3}];
}
getItems() {
this.collection = this.getItemsFromServer();
}
getItemsFromServer() {
return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
}
trackByFn(index, item) {
return index; // or item.id
}
}
NgNonBindable
NgNonbindable指令用于告诉Angular编译器,无需编译页面中某个特定的HTML代码片段
<div class='ngNonBindableDemo'>
<span class="bordered">{{ content }}</span>
<span class="pre" ngNonBindable>
← This is what {{ content }} rendered
</span>
</div>
Angular4.x新特性
If...Else Template Conditions
语法
<element *ngIf="[condition expression]; else [else template]"></element>
使用实例
<ng-template #hidden>
<p>You are not allowed to see our secret</p>
</ng-template>
<p *ngIf="shown; else hidden">
Our secret is being happy
</p>
<
template> --><
ng-template>
使用实例
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';
@Component({
selector: 'exe-app',
template: `
<ng-template #fetching>
<p>Fetching...</p>
</ng-template>
<p *ngIf="auth | async; else fetching; let user">
{{user.username }}
</p>
`,
})
export class AppComponent implements OnInit {
auth: Observable<{}>;
ngOnInit() {
this.auth = Observable
.of({ username: 'semlinker', password: 'segmentfault' })
.delay(new Date(Date.now() + 2000));
}
}
NOTE:
使用[hidden]属性控制元素可见性存在的问题
<div [hidden]="!showGreeting">
Hello, there!
</div>
上面的代码在通常情况下,都能正常工作。但当在对应的DOM元素位置上设置display:flex属性时,尽管[hidden]对应的表达式true,但元素却能正常显示。对于这种特殊情况,则推荐使用*ngIf。
直接使用 DOM API 获取页面上的元素存在的问题
@Component({
selector: 'my-comp',
template: `
<input type="text" />
<div> Some other content </div>
`
})
export class MyComp {
constructor(el: ElementRef) {
el.nativeElement.querySelector('input').focus();
}
}
以上的代码直接通过 querySelector() 获取页面中的元素,通常不推荐使用这种方式。更好的方案是使用 @ViewChild 和模板变量,具体示例如下:
@Component({
selector: 'my-comp',
template: `
<input #myInput type="text" />
<div> Some other content </div>
`
})
export class MyComp implements AfterViewInit {
@ViewChild('myInput') input: ElementRef;
constructor(private renderer: Renderer) {}
ngAfterViewInit() {
this.renderer.invokeElementMethod(
this.input.nativeElement, 'focus');
}
}
另外值得注意的是,@ViewChild() 属性装饰器,还支持设置返回对象的类型,具体使用方式如下:
@ViewChild('myInput') myInput1: ElementRef;
@ViewChild('myInput', {read: ViewContainerRef}) myInput2: ViewContainerRef;
若未设置 read 属性,则默认返回的是 ElementRef 对象实例。
Angular4之常用指令的更多相关文章
- linux常用指令
整理下来的linux常用指令 mount [-t 文件系统] 设备文件名 挂载点挂载命令,一般用于在挂载ISO,或者其他比如U盘等设备时使用,[-t iso9660]为固定格式,可写可不写,非必写项. ...
- 走进AngularJs(二) ng模板中常用指令的使用方式
通过使用模板,我们可以把model和controller中的数据组装起来呈现给浏览器,还可以通过数据绑定,实时更新视图,让我们的页面变成动态的.ng的模板真是让我爱不释手.学习ng道路还很漫长,从模板 ...
- mac 终端 常用指令
开始正式研究ios 应用开发,由于是从C开始学起,所以学习下常用的mac终端指令,方便后续常用操作. mac 终端 常用指令: 1.ls指令 用途:列出文件 常用参数 -w 以简洁的形式列出所有文件和 ...
- ImageMagick常用指令详解
Imagemagick常用指令 (ImageMagick--蓝天白云) (ImageMagick官网) (其他比较有价值的IM参考) (图片自动旋转的前端实现方案) convert 转换图像格式和大小 ...
- [AngularJS] 常用指令
常用指令 ng-hide指令,用于控制部分HTML元素可见(ng-hide="false")和不可见状态(ng-hide="true"),如下: <div ...
- iOS开发——源代码管理——git(分布式版本控制和集中式版本控制对比,git和SVN对比,git常用指令,搭建GitHub远程仓库,搭建oschina远程仓库 )
一.git简介 什么是git? git是一款开源的分布式版本控制工具 在世界上所有的分布式版本控制工具中,git是最快.最简单.最流行的 git的起源 作者是Linux之父:Linus Bened ...
- linux下svn常用指令
windows下的TortoiseSVN是资源管理器的一个插件,以覆盖图标表示文件状态,几乎所以命令都有图形界面支持,比较好用,这里就不多说.主要说说linux下svn的使用,因为linux下大部分的 ...
- [转载]linux下svn常用指令
一下内容转载于:http://blog.chinaunix.net/space.php?uid=22976768&do=blog&id=1640924.这个总结的很好~ windows ...
- ARM汇编常用指令
RAM汇编常用指令有MOV B BL LDR STR
随机推荐
- matlab reshape()、full()
一.reshape() 对于这个函数,就是重构矩阵. (1)要求:重构前后的矩阵元素个数一致.如3*4矩阵可以重构成2*6,2*3*2等. (2)重构方法:先按列将矩阵转换为向量,然后在向量的基础之上 ...
- 设置ip地址、掩码、网关、DNS
@echo offcolor f8mode con cols=40 lines=8echo.echo.echo 设置IP为:echo.set /p ip= 192. ...
- 在windows下制作mac os x的启动安装U盘
前几天有幸用了下Macbook pro,可在给它装win 7系统时,无知而又手贱地在windows系统下分区了:( 然后再重启就找不到Mac os x,只有win 7了.可进win 7也不正常,直接给 ...
- springboot项目搭建
https://blog.csdn.net/u012702547/article/details/54319508
- 编译libmad库
libmad是一个开源的音频解码库,下面说说关于这个库工程的编译过程: 1.首先从网上下载libmad开源库,自己百度就能够找到关于这个库的下载链接地址,我这里提供一个: http://downloa ...
- WPF 多线程异常抛送到UI线程
无论是winform还是WPF,在.NET 2.0之后 只要是多线程中产生了异常都会导致程序强制结束. 那么我们一般的做法是将未知的多线程的异常抛送到UI线程去,然后进行处理.. 正确的多线程中的异常 ...
- java开发中的常见类和对象-建议阅读时间3分钟
1.Dao 数据访问对象 此对象用于访问数据库.实现类一般用于用于操作数据库! 一般操作修改,添加,删除数据库操作的步骤很相似,就写了一个公共类DAO类 ,修改,添加,删除数据库操作时 直接调用公共类 ...
- Jmeter参数跨线程组传递
1.利用BeanShell, 请求==>后置==>beanshellpostprocessorScripts内写:props.put("user_name"," ...
- import和export语法报错
“最近在学习ES6”,但是在chrome中新建了js通过ES6语法(import,export)无法引入外部JS,报错: Uncaught SyntaxError:Unexpected token { ...
- bat文件:启动,休眠VBox虚拟机
1. start.Xp_Mysql.bat @echo cd D:\Program Files\VirtualBox\ D: .\VBoxManage startvm Xp_Mysql --type ...