Angular基礎語法詳解

插值
文本綁定
<p>Message: {{ msg }}</p>
<p [innerHTML]="msg"></p>屬性綁定
<!-- 寫法一 -->
<img src="{{ heroImageUrl }}">
<!-- 寫法二,推薦 -->
<img [src]="heroImageUrl">
<!-- 寫法三 -->
<img bind-src="heroImageUrl">在布爾特性的情況下,它們的存在即暗示為 true,屬性綁定工作起來略有不同,在這個例子中:
<button [disabled]="isButtonDisabled">Button</button>
如果 isButtonDisabled 的值是 null、undefined 或 false,則 disabled 特性甚至不會被包含在渲染出來的 <button> 元素中。
使用 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 表達式也是合法的模板表達式,但不是全部。
Angular 遵循輕邏輯的設計思路,所以在模板引擎中不能編寫非常復雜的 JavaScript 表達式,這里有一些約定:
- 賦值 (
=,+=,-=, …) new運算符- 使用
;或,的鏈式表達式 - 自增或自減操作符 (
++和--)
列表渲染
基本用法:
export class AppComponent {
heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
}
<p>Heroes:</p>
<ul>
<li *ngFor="let hero of heroes">
{{ hero }}
</li>
</ul>
也可以獲取 index 索引:
<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 的語法比較啰嗦,使用頻率小一些。
<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>

事件處理
事件綁定只需要用圓括號把事件名包起來即可:
<button (click)="onSave()">Save</button>
可以把事件對象傳遞到事件處理函數(shù)中:
<button (click)="onSave($event)">On Save</button>
也可以傳遞額外的參數(shù)(取決于你的業(yè)務):
<button (click)="onSave($event, 123)">On Save</button>
當事件處理語句比較簡單的時候,我們可以內聯(lián)事件處理語句:
<button (click)="message = '哈哈哈'">內聯(lián)事件處理</button>
我們可以利用 屬性綁定 + 事件處理 的方式實現(xiàn)表單文本框雙向綁定:
<input [value]="message"
(input)="message=$event.target.value" >
事件綁定的另一種寫法,使用 on- 前綴的方式:
<!-- 綁定事件處理函數(shù) --> <button on-click="onSave()">On Save</button>
表單輸入綁定
文本
<p>{{ message }}</p>
<input type="text" [(ngModel)]="message">
運行之后你會發(fā)現(xiàn)報錯了,原因是使用 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 中使用雙向數(shù)據(jù)綁定了??。
多行文本
<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 給定一個布爾值,當布爾值為真則作用該類名,當布爾值為假則移除給類名。
語法規(guī)則:
<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
通過樣式綁定,可以設置內聯(lián)樣式。
樣式綁定的語法與屬性綁定類似。 但方括號中的部分不是元素的屬性名,而由style前綴,一個點 (.)和 CSS 樣式的屬性名組成。 形如:[style.style-property]。
<button [style.color]="isSpecial ? 'red': 'green'">Red</button> <!-- 也可以 backgroundColor --> <button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>
有些樣式綁定中的樣式帶有單位。在這里,以根據(jù)條件用 “em” 和 “%” 來設置字體大小的單位。
<button [style.font-size.em]="isSpecial ? 3 : 1" >Big</button> <button [style.font-size.%]="!isSpecial ? 150 : 50" >Small</button>
NgStyle 指令
雖然這是設置單一樣式的好辦法,但我們通常更喜歡使用 NgStyle指令 來同時設置多個內聯(lián)樣式。
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>
大多數(shù)情況下,Angular會把模板引用變量的值設置為聲明它的那個元素。在上面例子中,
phone引用的是表示電話號碼的<input>框。 "撥號"按鈕的點擊事件處理器把這個input值傳給了組件的callPhone方法。 不過,指令也可以修改這種行為,讓這個值引用到別處,比如它自身。NgForm指令就是這么做的。
模板引用變量使用注意:
- 模板引用變量的作用范圍是整個模板。 不要在同一個模板中多次定義同一個變量名,否則它在運行期間的值是無法確定的。
- 如果我在模板里面定義的局部變量和組件內部的屬性重名會怎么樣呢
- 如果真的出現(xiàn)了重名,Angular 會按照以下優(yōu)先級來進行處理
模板局部變量 > 指令中的同名變量 > 組件中的同名屬性
- 我們也可以用
ref-前綴代替#。 下面的例子中就用把fax變量聲明成了ref-fax而不是#fax。
<input ref-fax placeholder="fax number"> <button (click)="callFax(fax.value)">Fax</button>
過濾器
在 Angular 中,過濾器也叫管道。它最重要的作用就是用來格式化數(shù)據(jù)的輸出。
舉個簡單例子:
public currentTime: Date = new Date();
<h1>{{currentTime | date:'yyyy-MM-dd HH:mm:ss'}}</h1>
Angular 一共內置了16個過濾器:https://angular.io/api?type=pipe。
在復雜業(yè)務場景中,內置的過濾器肯定是不夠用的,所有 Angular 也支持自定義過濾器。
管道還有另外一個重要的作用就是做國際化。
到此這篇關于Angular【基礎語法】的文章就介紹到這了,更多相關Angular基礎語法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解基于Bootstrap+angular的一個豆瓣電影app
本篇文章主要介紹了基于Bootstrap+angular的一個豆瓣電影app ,非常具有實用價值,需要的朋友可以參考下2017-06-06
AngularJS實現(xiàn)的JSONP跨域訪問數(shù)據(jù)傳輸功能詳解
這篇文章主要介紹了AngularJS實現(xiàn)的JSONP跨域訪問數(shù)據(jù)傳輸功能,較為詳細的分析了JSONP的概念、功能并結合實例形式給出了AngularJS使用JSONP進行跨域訪問數(shù)據(jù)傳輸?shù)南嚓P技巧,需要的朋友可以參考下2017-07-07
Angularjs自定義指令實現(xiàn)分頁插件(DEMO)
由于最近的一個項目使用的是angularjs1.0的版本,涉及到分頁查詢數(shù)據(jù)的功能,后來自己就用自定義指令實現(xiàn)了該功能,下面小編把實例demo分享到腳本之家平臺,需要的朋友參考下2017-09-09

