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仿flash上传头像效果实现代码
Jul 18 Javascript
window.onload和$(function(){})的区别介绍
Oct 30 Javascript
jQuery实现点击按钮弹出可关闭层的浮动层插件
Sep 19 Javascript
鼠标悬停小图标显示大图标
Jan 22 Javascript
jQuery实现订单提交页发送短信功能前端处理方法
Jul 04 Javascript
推荐VSCode 上特别好用的 Vue 插件之vetur
Sep 14 Javascript
Angular5中调用第三方js插件的方法
Feb 26 Javascript
JS 音频可视化插件Wavesurfer.js的使用教程
Oct 31 Javascript
全面了解JavaScript的作用域链
Apr 03 Javascript
js常用方法、检查是否有特殊字符串、倒序截取字符串操作完整示例
Jan 26 Javascript
详解JavaScript中的链式调用
Nov 27 Javascript
js实现滚动条自动滚动
Dec 13 Javascript
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
我的论坛源代码(九)
2006/10/09 PHP
PHP获取MAC地址的具体实例
2013/12/13 PHP
PHP中使用file_get_contents抓取网页中文乱码问题解决方法
2014/12/17 PHP
PHP常用字符串函数用法实例总结
2020/06/04 PHP
php如何实现数据库的备份和恢复
2020/11/30 PHP
cookie丢失问题(认证失效) Authentication (用户验证信息)也会丢失
2009/06/04 Javascript
javascript下对于事件、事件流、事件触发的顺序随便说说
2010/07/17 Javascript
js判断IE浏览器版本过低示例代码
2013/11/22 Javascript
node.js中RPC(远程过程调用)的实现原理介绍
2014/12/05 Javascript
jQuery点击其他地方时菜单消失的实现方法
2016/04/22 Javascript
jQuery Tags Input Plugin(添加/删除标签插件)详解
2016/06/20 Javascript
Jquery实现上下移动和排序代码
2016/10/17 Javascript
利用js获取下拉框中所选的值
2016/12/01 Javascript
深入理解JavaScript中的for循环
2017/02/07 Javascript
JavaScript中数组Array方法详解
2017/02/27 Javascript
基于Vue实现tab栏切换内容不断实时刷新数据功能
2017/04/13 Javascript
angular4 如何在全局设置路由跳转动画的方法
2017/08/30 Javascript
[01:15:45]DOTA2上海特级锦标赛B组小组赛#1 Alliance VS Spirit第一局
2016/02/26 DOTA
Python数据结构与算法之完全树与最小堆实例
2017/12/13 Python
关于python列表增加元素的三种操作方法
2018/08/22 Python
python 快速把超大txt文件转存为csv的实例
2018/10/26 Python
利用Python检测URL状态
2019/07/31 Python
Python获取统计自己的qq群成员信息的方法
2019/11/15 Python
python使用gdal对shp读取,新建和更新的实例
2020/03/10 Python
python应用Axes3D绘图(批量梯度下降算法)
2020/03/25 Python
matplotlib基础绘图命令之bar的使用方法
2020/08/13 Python
英国领先的在线鱼贩:The Fish Society
2020/08/12 全球购物
简述DNS进行域名解析的过程
2013/12/02 面试题
不拖欠农民工工资承诺书
2014/03/31 职场文书
离职报告范文
2014/11/04 职场文书
党的群众路线教育实践活动个人对照检查材料(医生)
2014/11/05 职场文书
亲戚关系证明
2015/06/24 职场文书
2016年党风廉政建设承诺书
2016/03/25 职场文书
2016年学生会感恩节活动总结
2016/04/01 职场文书
Python爬虫之爬取二手房信息
2021/04/27 Python
JS不要再到处使用绝对等于运算符了
2021/04/30 Javascript