Angular4 中常用的指令入门总结


Posted in Javascript onJune 12, 2017

前言

本文主要给大家介绍了关于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 属性。

1、设置元素的背景颜色

<div [style.background-color="'yellow'"]>
 Use fixed yellow background
</div>

2、设置元素的字体大小

<!-- 支持单位: 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 ,所以需要添加 ''。

NgClass

NgClass 接收一个对象字面量,对象的 key 是 CSS class 的名称,value 的值是 truthy/falsy 的值,表示是否应用该样式。

1、CSS Class

.bordered {
 border: 1px dashed black; background-color: #eee;
}

2、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>

Angular 4.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));
 }
}

我有话说

使用 [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 对象实例。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Javascript 相关文章推荐
js类的静态属性和实例属性的理解
Oct 01 Javascript
基于jquery tab切换(防止页面刷新)
May 23 Javascript
浅谈JavaScript之事件绑定
Jul 08 Javascript
轻量级网页遮罩层jQuery插件用法实例
Jul 31 Javascript
JavaScript设计模式之单体模式全面解析
Sep 09 Javascript
js仿iphone秒表功能 计算平均数
Jan 11 Javascript
浅谈JavaScript正则表达式-非捕获性分组
Mar 08 Javascript
TypeScript的安装、使用、自动编译的实现
Apr 10 Javascript
详解JavaScript之ES5的继承
Jul 08 Javascript
一行JavaScript代码如何实现瀑布流布局
Dec 11 Javascript
js中延迟加载和预加载的具体使用
Jan 14 Javascript
vue使用过滤器格式化日期
Jan 20 Vue.js
Node.js 8 中的 util.promisify的详解
Jun 12 #Javascript
jquery处理checkbox(复选框)是否被选中实例代码
Jun 12 #jQuery
实现微信小程序的wxml文件和wxss文件在webstrom的支持
Jun 12 #Javascript
JavaScript初学者必看“new”
Jun 12 #Javascript
详解vue.js 开发环境搭建最简单攻略
Jun 12 #Javascript
Ionic + Angular.js实现验证码倒计时功能的方法
Jun 12 #Javascript
微信小程序 实现点击添加移除class
Jun 12 #Javascript
You might like
PHP获取用户的浏览器与操作系统信息的代码
2012/09/04 PHP
使用php将某个目录下面的所有文件罗列出来的方法详解
2013/06/21 PHP
php rmdir使用递归函数删除非空目录实例详解
2016/10/20 PHP
PHP设计模式之注册树模式分析
2018/01/26 PHP
Jquery 滑入滑出效果实现代码
2010/03/27 Javascript
js禁止小键盘输入数字功能代码
2011/08/01 Javascript
JavaScript简单表格编辑功能实现方法
2015/04/16 Javascript
jquery实现图片左右切换的方法
2015/05/07 Javascript
详解jQuery简单的表格应用
2016/12/16 Javascript
Bootstrap3 模态框使用实例
2017/02/22 Javascript
jQuery ajax实现省市县三级联动
2021/03/07 Javascript
深入理解JavaScript 参数按值传递
2017/05/24 Javascript
JS之if语句对接事件动作逻辑(详解)
2017/06/28 Javascript
vue使用laydate时间插件的方法
2018/11/14 Javascript
微信小程序调用微信支付接口的实现方法
2019/04/29 Javascript
vue 组件内获取actions的response方式
2019/11/08 Javascript
python网络爬虫采集联想词示例
2014/02/11 Python
python实现通过pil模块对图片格式进行转换的方法
2015/03/24 Python
python获取一组数据里最大值max函数用法实例
2015/05/26 Python
python psutil库安装教程
2018/03/19 Python
python读取和保存视频文件
2018/04/16 Python
浅谈Python2、Python3相对路径、绝对路径导入方法
2018/06/22 Python
详解python持久化文件读写
2019/04/06 Python
python实现银联支付和支付宝支付接入
2019/05/07 Python
python解压TAR文件至指定文件夹的实例
2019/06/10 Python
Ubuntu18.04下python版本完美切换的解决方法
2019/06/14 Python
pytorch 实现将自己的图片数据处理成可以训练的图片类型
2020/01/08 Python
Tensorflow设置显存自适应,显存比例的操作
2020/02/03 Python
手把手教你安装Windows版本的Tensorflow
2020/03/26 Python
jupyter note 实现将数据保存为word
2020/04/14 Python
Pandas的Apply函数具体使用
2020/07/21 Python
Python pathlib模块使用方法及实例解析
2020/10/05 Python
BOSE德国官网:尽探索之力,享音乐之极
2016/12/11 全球购物
新电JAVA笔试题目
2014/08/31 面试题
高中生职业规划范文
2014/03/09 职场文书
村主任个人对照检查材料
2014/10/01 职场文书