angular 模板语法

2019-08-05  本文已影响0人  不染事非
1.插值表达式 (Interpolation) {{...}}
<p>The sum of 1 + 1 is {{1 + 1}}</p>
2.表达式上下文 (Expression context)
{{title}}
<span [hidden]="isUnchanged">changed</span>

二.绑定语法

绑定的类型可以根据数据流的方向分成三类:

单向 source-to-view

语法 绑定类型
{{expression}} 插值表达式
[target]="expression" / bind-target="expression" Property, Attribute 类样式

单向 view-to-source

语法 绑定类型
(target)="statement" / on-target="statement" 事件

双向

语法 绑定类型
[(target)]="expression" / bindon-target="expression" 双向

绑定类型(插值表达式除外)有一个目标名,它位于等号左边,它是 Property 的名字(注意它不是 Attribute 的名字)。

绑定目标 (Binding targets)

Property 绑定类型
目标 范例
Element property <img [src]="heroImageUrl">
Component property <hero-detail [hero]="currentHero"></hero-detail>
Directive property <div [ngClass]="{special: isSpecial}"></div>
事件绑定类型
目标 范例
Element event <button (click)="onSave()">Save</button>
Component event <hero-detail (deleteRequest)="deleteHero()"></hero-detail>
Directive event <div (myClick)="clicked=$event" clickable>click me</div>
双向绑定类型
目标 范例
Event and property <input [(ngModel)]="name">
Attribute 绑定类型
目标 范例
Attribute(例外情况) <button [attr.aria-label]="help">help</button>
CSS 类绑定类型
目标 范例
class property <div [class.special]="isSpecial">Special</div>
样式绑定类型
目标 范例
style property <button [style.color]="isSpecial ? 'red' : 'green'">
属性绑定 (Property binding) [property]
<img [src]="heroImageUrl">

上例说明:image 元素的 src 属性会被绑定到组件的 heroImageUrl 属性上。

绑定目标

两种写法:

<img [src]="heroImageUrl">

![](heroImageUrl)

三.内置指令

常见的内置属性型指令:

NgClass

示例:组件方法 setCurrentClasses 可以把组件的属性 currentClasses 设置为一个对象,它将会根据三个其它组件的状态为 true 或 false 而添加或移除三个类

currentClasses: {};
setCurrentClasses() {
  this.currentClasses =  {
    saveable: this.canSave,
    modified: !this.isUnchanged,
    special:  this.isSpecial
  };
}

把 ngClass 属性绑定到 currentClasses,根据它来设置此元素的 CSS 类:

<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>
NgStyle

ngStyle 需要绑定到一个 key:value 控制对象。 对象的每个 key 是样式名,它的 value 是能用于这个样式的任何值。

currentStyles: {};
setCurrentStyles() {
  // CSS styles: set per current state of component properties
  this.currentStyles = {
    'font-style':  this.canSave      ? 'italic' : 'normal',
    'font-weight': !this.isUnchanged ? 'bold'   : 'normal',
    'font-size':   this.isSpecial    ? '24px'   : '12px'
  };
}

<div [ngStyle]="currentStyles">
  This div is initially italic, normal weight, and extra large (24px).
</div>
NgModel

要使用 ngModel 需要导入 FormsModule 模块。

import { NgModule } from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular

/* Other imports */
@NgModule({
  imports: [
    BrowserModule,
    FormsModule  // <--- import into the NgModule
  ],
  /* Other module metadata */
})
export class AppModule { }

使用 ngModel 实现双向数据绑定。

<input [(ngModel)]="currentHero.name">

该语句实际上隐藏了其实现细节:

<input [ngModel]="currentHero.name"
       (ngModelChange)="currentHero.name=$event">

如果需要做一些不同的处理,就不能使用 [(ngModel)] 语法,而应写成扩展的方式:

<input [ngModel]="currentHero.name"
       (ngModelChange)="setUppercaseName($event)">

ngModel 指令只能用在支持 ControlValueAccessor 的元素上。

四. 内置结构型指令

常见的内置结构型指令:

NgIf
<hero-detail *ngIf="isActive"></hero-detail>

别忘了 ngIf 前面的星号( * )。

NgFor
<div *ngFor="let hero of heroes">{{hero.name}}</div>
NgSwitch

NgSwitch 由三个指令组成:

<div [ngSwitch]="currentHero.emotion">
  <happy-hero    *ngSwitchCase="'happy'"    [hero]="currentHero"></happy-hero>
  <sad-hero      *ngSwitchCase="'sad'"      [hero]="currentHero"></sad-hero>
  <confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></confused-hero>
  <unknown-hero  *ngSwitchDefault           [hero]="currentHero"></unknown-hero>
</div>
模板引用变量

使用井号 # (或 ref-)来声明一个模板引用变量。The#phone declares a phone variable on an <input> element.

<input #phone placeholder="phone number">
或者写成
<input ref-phone placeholder="phone number">
输入输出属性 @Input 和 @Output
声明输入和输出属性(目标属性必须被显式的标记为输入或输出。)

HeroDetailComponent.hero 是属性绑定的目标。 HeroDetailComponent.deleteRequest 是事件绑定的目标。

<hero-detail [hero]="currentHero" (deleteRequest)="deleteHero($event)">
</hero-detail>

方法1:使用装饰器 @Input() 和 @Output()。

@Input()  hero: Hero;
@Output() deleteRequest = new EventEmitter<Hero>();

方法2:通过元数据数组。

@Component({
  inputs: ['hero'],
  outputs: ['deleteRequest'],
})

两种方法不可同时使用。

给输入输出属性起别名

方法1:把别名传进 @Input / @Output 装饰器,就可以为属性指定别名:

@Output('myClick') clicks = new EventEmitter<string>(); //  @Output(alias) propertyName = ...

方法2:在 inputs 和 outputs 数组中为属性指定别名。 语法(属性名:别名)

@Directive({
  outputs: ['clicks:myClick']  // propertyName:alias
})

模板表达式操作符

管道操作符 |

管道是一个简单的函数,它接受一个输入值,并返回转换结果。

<div>Title through uppercase pipe: {{title | uppercase}}</div>

还能对管道使用参数:

<div>Birthdate: {{currentHero?.birthdate | date:'longDate'}}</div>
安全导航操作符 ( ?. ) 和空属性路径

Angular 的安全导航操作符 (?.) 用来保护出现在属性路径中 null 和 undefined 值。示例:

The current hero's name is {{currentHero?.name}}

说明:当 currentHero 为空时,保护视图渲染器,让它免于失败。

上一篇 下一篇

猜你喜欢

热点阅读