博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Angular 4.x template syntax & common directives
阅读量:6991 次
发布时间:2019-06-27

本文共 4931 字,大约阅读时间需要 16 分钟。

阅读 Angular 6/RxJS 最新教程,请访问

模板语法简介

插值表达式

Hello {
{name}}

等价于

模板表达式

属性绑定

输入属性的值为常量

等价于

输入属性的值为实例属性

等价于

事件绑定

等价于

模板引用变量

等价于

双向绑定

等价于

*<template>

*ngIf

最终转换为

*ngFor

最终转换为

常用指令简介

NgIf

NgSwitch

有时候需要根据不同的条件,渲染不同的元素,此时我们可以使用多个 ngIf 来实现。

Var is A
Var is B
Var is something else

如果 myVar 的可选值多了一个 'C',就得相应增加判断逻辑:

Var is A
Var is B
Var is C
Var is something else

可以发现 Var is something else 的判断逻辑,会随着 myVar 可选值的新增,变得越来越复杂。遇到这种情景,我们可以使用 ngSwitch 指令。

Var is A
Var is B
Var is C
Var is something else

NgStyle

NgStyle 让我们可以方便得通过 Angular 表达式,设置 DOM 元素的 CSS 属性。

  • 设置元素的背景颜色
Use fixed yellow background
  • 设置元素的字体大小
red text

NgStyle 支持通过键值对的形式设置 DOM 元素的样式:

Uses fixed white text on blue background

注意到 background-color 需要使用单引号,而 color 不需要。这其中的原因是,ng-style 要求的参数是一个 Javascript 对象,color 是一个有效的 key,而 background-color 不是一个有效的 key ,所以需要添加 ''

NgStyle 源码片段
@Directive({selector: '[ngStyle]'})export class NgStyle implements DoCheck {  private _ngStyle: {[key: string]: string};  private _differ: KeyValueDiffer
; constructor( private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {} @Input() set ngStyle(v: {[key: string]: string}) { //
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
This is never bordered
This is always bordered
Using object literal. Border {
{ isBordered ? "ON" : "OFF" }}
Class names contains dashes must use single quote
This will always have a blue background and round corners

NgFor

NgFor 指令用来根据集合(数组) ,创建 DOM 元素,类似于 ng1ng-repeat 指令

{
{ num+1 }} - {
{ c }}

使用 trackBy 提高列表的性能

@Component({  selector: 'my-app',  template: `    
  • {
    {item.id}}
`,})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代码片段。

{
{ content }}
← This is what {
{ content }} rendered

Angular 4.x 新特性

If...Else Template Conditions

语法

使用示例

You are not allowed to see our secret

Our secret is being happy

<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: `   

Fetching...

{

{user.username }}

`,})export class AppComponent implements OnInit { auth: Observable<{}>; ngOnInit() { this.auth = Observable .of({ username: 'semlinker', password: 'segmentfault' }) .delay(new Date(Date.now() + 2000)); }}

我有话说

使用 [hidden] 属性控制元素可见性存在的问题

Hello, there!

上面的代码在通常情况下,都能正常工作。但当在对应的 DOM 元素上设置 display: flex 属性时,尽管[hidden] 对应的表达式为 true,但元素却能正常显示。对于这种特殊情况,则推荐使用 *ngIf

直接使用 DOM API 获取页面上的元素存在的问题

@Component({  selector: 'my-comp',  template: `        
Some other content
`})export class MyComp { constructor(el: ElementRef) { el.nativeElement.querySelector('input').focus(); }}

以上的代码直接通过 querySelector() 获取页面中的元素,通常不推荐使用这种方式。更好的方案是使用 @ViewChild 和模板变量,具体示例如下:

@Component({  selector: 'my-comp',  template: `        
Some other content
`})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 对象实例。

转载地址:http://qfdvl.baihongyu.com/

你可能感兴趣的文章
Servlet的Web访问名称与Servlet家族简介
查看>>
第一次来
查看>>
Linux命令记录神器history命令基础6
查看>>
TurboMail邮件系统再次通过涉密软件认证
查看>>
JAVA之JNI从头完整实例
查看>>
win10安装解压缩版mysql5.7.25(图解)
查看>>
python redis 分页
查看>>
nmap教程之nmap命令使用示例(nmap使用方法) 服务器***利器
查看>>
[转载] 七龙珠第一部——第118话 天津饭的决心
查看>>
ORACLE DATAGUARD 11G R2 RAC TO RAC
查看>>
AIX slibclean
查看>>
用fopen,fseek,ftell,fread读取文件
查看>>
一些常见的基础命令
查看>>
PageRank算法概述
查看>>
Servlet中的监听器及监听在线人数实例
查看>>
node.js学习之swig
查看>>
更改进程名称-prctl
查看>>
我用到的linux软件安装命令
查看>>
openSSL制作简单的服务器端和客户端证书
查看>>
分享:揭秘Android恶意App挣钱的诀窍!
查看>>