ng-模板語法

插值

文本綁定

<p>Message: {{ msg }}</p>

<p [innerHTML]="msg"></p>

屬性綁定

<!-- 寫法一 -->
<img src="{{ heroImageUrl }}">

<!-- 寫法二,推薦 -->
<img [src]="heroImageUrl">

<!-- 寫法三 -->
<img bind-src="heroImageUrl">

在布爾特性的狀況下,它們的存在即暗示爲 true,屬性綁定工做起來略有不一樣,在這個例子中:javascript

<button [disabled]="isButtonDisabled">Button</button>

若是 isButtonDisabled 的值是 nullundefinedfalse,則 disabled 特性甚至不會被包含在渲染出來的 <button> 元素中。css

使用 JavaScript 表達式

<p>1 + 1 = {{ 1 + 1 }}</p>
<p>{{ num + 1 }}</p>
<p>{{ isDone ? '完了' : '沒完' }}</p>
<p>{{ title.split('').reverse().join('') }}</p>

<p [title]="title.split('').reverse().join('')">{{ title }}</p>

<ul>
  <li [id]="'list-' + t.id" *ngFor="let t of todos">
    {{ t.title }}
  </li>
</ul>

編寫模板表達式所用的語言看起來很像 JavaScript。 不少 JavaScript 表達式也是合法的模板表達式,但不是所有。html

Angular 遵循輕邏輯的設計思路,因此在模板引擎中不能編寫很是複雜的 JavaScript 表達式,這裏有一些約定:java

  • 賦值 (=, +=, -=, ...)
  • new 運算符
  • 使用 ;, 的鏈式表達式
  • 自增或自減操做符 (++--)

列表渲染

基本用法:typescript

export class AppComponent {
  heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
}
<p>Heroes:</p>
<ul>
  <li *ngFor="let hero of heroes">
    {{ hero }}
  </li>
</ul>

也能夠獲取 index 索引:bootstrap

<div *ngFor="let hero of heroes; let i=index">{{i + 1}} - {{hero.name}}</div>

條件渲染

NgIf

<p *ngIf="heroes.length > 3">There are many heroes!</p>

ngIf<ng-template>

<ng-template [ngIf]="condition"><div>...</div></ng-template>

NgSwitch

NgSwitch 的語法比較囉嗦,使用頻率小一些。api

<div [ngSwitch]="currentHero.emotion">
  <app-happy-hero    *ngSwitchCase="'happy'"    [hero]="currentHero"></app-happy-hero>
  <app-sad-hero      *ngSwitchCase="'sad'"      [hero]="currentHero"></app-sad-hero>
  <app-confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></app-confused-hero>
  <app-unknown-hero  *ngSwitchDefault           [hero]="currentHero"></app-unknown-hero>
</div>

ngswitch

事件處理

事件綁定只須要用圓括號把事件名包起來便可:app

<button (click)="onSave()">Save</button>

能夠把事件對象傳遞到事件處理函數中:curl

<button (click)="onSave($event)">On Save</button>

也能夠傳遞額外的參數(取決於你的業務):ide

<button (click)="onSave($event, 123)">On Save</button>

當事件處理語句比較簡單的時候,咱們能夠內聯事件處理語句:

<button (click)="message = '哈哈哈'">內聯事件處理</button>

咱們能夠利用 屬性綁定 + 事件處理 的方式實現表單文本框雙向綁定:

<input [value]="message"
       (input)="message=$event.target.value" >

事件綁定的另外一種寫法,使用 on- 前綴的方式:

<!-- 綁定事件處理函數 -->
<button on-click="onSave()">On Save</button>

表單輸入綁定

文本

<p>{{ message }}</p>
<input type="text" [(ngModel)]="message">

運行以後你會發現報錯了,緣由是使用 ngModel 必須導入 FormsModule 並把它添加到 Angular 模塊的 imports 列表中。

導入 FormsModule 並讓 [(ngModel)] 可用的代碼以下:

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

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
+++ FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

經過以上的配置以後,你就能夠開心的在 Angular 中使用雙向數據綁定了😊。

多行文本

<textarea cols="30" rows="10" [(ngModel)]="message"></textarea>

複選框

<h3>單選框</h3>
<input type="checkbox" [(ngModel)]="seen">
<div class="box" *ngIf="seen"></div>

單選按鈕

<input type="radio" [value]="0" [(ngModel)]="gender"> 男
<input type="radio" [value]="1" [(ngModel)]="gender"> 女
<p>選中了:{{ gender }}</p>

下拉列表

<select [(ngModel)]="hobby">
  <option [value]="0">吃飯</option>
  <option [value]="1">睡覺</option>
  <option [value]="2">打豆豆</option>
</select>
<p>選中的愛好:{{ hobby }}</p>

Class 與 Style 綁定

Class

  • https://angular.io/guide/template-syntax#ngClass
<!-- standard class attribute setting  -->
<div class="bad curly special">Bad curly special</div>

<!-- reset/override all class names with a binding  -->
<div class="bad curly special"
     [class]="badCurly">Bad curly</div>

<!-- toggle the "special" class on/off with a property -->
<div [class.special]="isSpecial">The class binding is special</div>

<!-- binding to `class.special` trumps the class attribute -->
<div class="special"
     [class.special]="!isSpecial">This one is not so special</div>

NgClass 指令

NgClass 指令接收一個對象,對象的 key 指定 css 類名,value 給定一個布爾值,當布爾值爲真則做用該類名,當布爾值爲假則移除給類名。

語法規則:

<div [ngClass]="{
  css類名: 布爾值,
  css類名: 布爾值
}">測試文本</div>

基本示例:

.saveable{
    font-size: 18px;
} 
.modified {
    font-weight: bold;
}
.special{
    background-color: #ff3300;
}
currentClasses: {};
setCurrentClasses() {
  // CSS classes: added/removed per current state of component properties
  this.currentClasses =  {
    'saveable': this.canSave,
    'modified': !this.isUnchanged,
    'special':  this.isSpecial
  };
}
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>

Style

經過樣式綁定,能夠設置內聯樣式。

樣式綁定的語法與屬性綁定相似。 但方括號中的部分不是元素的屬性名,而由style前綴,一個點 (.)和 CSS 樣式的屬性名組成。 形如:[style.style-property]

<button [style.color]="isSpecial ? 'red': 'green'">Red</button>
<!-- 也能夠 backgroundColor -->
<button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>

有些樣式綁定中的樣式帶有單位。在這裏,以根據條件用 「em」 和 「%」 來設置字體大小的單位。

<button [style.font-size.em]="isSpecial ? 3 : 1" >Big</button>
<button [style.font-size.%]="!isSpecial ? 150 : 50" >Small</button>

提示:樣式屬性命名方法能夠用中線命名法,像上面的同樣 也能夠用駝峯式命名法,如fontSize

NgStyle 指令

雖然這是設置單同樣式的好辦法,但咱們一般更喜歡使用 NgStyle指令 來同時設置多個內聯樣式。

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>

ngStyle 這種方式至關於在代碼裏面寫 CSS 樣式,比較醜陋,違反了注意點分離的原則,並且未來不太好修改,很是不建議這樣寫(足夠簡單的狀況除外)。

Angular 中的計算屬性

模板引用變量

模板引用變量一般用來引用模板中的某個DOM元素,它還能夠引用Angular組件或指令或Web Component

使用井號 (#) 來聲明引用變量。 #phone的意思就是聲明一個名叫phone的變量來引用<input>元素。

<input #phone placeholder="phone number">

咱們能夠在模板中的任何地方引用模板引用變量。 好比聲明在<input>上的phone變量就是在模板另外一側的<button>上使用的。

<input #phone placeholder="phone number">

<!-- lots of other elements -->

<!-- phone refers to the input element; pass its `value` to an event handler -->
<button (click)="callPhone(phone.value)">Call</button>

大多數狀況下,Angular會把模板引用變量的值設置爲聲明它的那個元素。在上面例子中,phone 引用的是表示電話號碼<input>框。 "撥號"按鈕的點擊事件處理器把這個input值傳給了組件的callPhone方法。 不過,指令也能夠修改這種行爲,讓這個值引用到別處,好比它自身。 NgForm指令就是這麼作的。

模板引用變量使用注意:

  • 模板引用變量的做用範圍是整個模板。 不要在同一個模板中屢次定義同一個變量名,不然它在運行期間的值是沒法肯定的。
  • 若是我在模板裏面定義的局部變量和組件內部的屬性重名會怎麼樣呢
    • 若是真的出現了重名,Angular 會按照如下優先級來進行處理
    • 模板局部變量 > 指令中的同名變量 > 組件中的同名屬性
  • 咱們也能夠用ref-前綴代替#。 下面的例子中就用把fax變量聲明成了ref-fax而不是#fax
<input ref-fax placeholder="fax number">
<button (click)="callFax(fax.value)">Fax</button>

過濾器

在 Angular 中,過濾器也叫管道。它最重要的做用就是用來格式化數據的輸出。

舉個簡單例子:

public currentTime: Date = new Date();
<h1>{{currentTime | date:'yyyy-MM-dd HH:mm:ss'}}</h1>

Angular 一共內置了16個過濾器:https://angular.io/api?type=pipe。

在複雜業務場景中,內置的過濾器確定是不夠用的,全部 Angular 也支持自定義過濾器。

管道還有另一個重要的做用就是作國際化。

相關文章
相關標籤/搜索