Angular2的核心概念詳解
阿新 • • 發佈:2021-01-15
2-1 元件及元件樹
8個核心概念
- 元件 Components
- 元資料 Metadata
- 模板 Templates
- 資料繫結 Data binding
- 服務 Services
- 指令 Directives
- 依賴注入 Dependency Injection
- 模組 Modules
元件
元件要素
HTML、CSS、JavaScript
全生命週期支援
- Constructor 構造器初始化
- OnChanges 第一次觸發資料變化鉤子
- OnInit 元件初始化(建議將和業務相關的初始化放到這裡)
- OnChanges 執行期間觸發資料變化鉤子
- OnDestroy 元件銷燬前
元件示例
// 裝飾器
@Component({
selector: 'hello',
template: '<p>{{greeting}}</p>'
})
// 元件類
export class HelloComponent {
private greeting: string;
constructor() {
this.greeting = 'Hello, Angular 2!'
}
}
元資料與裝飾器
普通類 + 裝飾器(@Component,包含元資料) => 元件
裝飾器用於賦予一個類更豐富的資訊(元資料),可以學習“reflect-metadata”庫。
模板
- 內聯模板:template
- 外聯模板:templateUrl
資料繫結
資料繫結方式
- 插值:{{interpolation}}
- 屬性繫結:[value]
<input [value]="myData" />
- 事件繫結:(keyup)
<input (keyup)="handle($event)" />
- 雙向繫結:[(ngModel)]
<input [(ngModel)]="myData" />
元件樹
元件渲染
2-2 指令
2-3 服務與依賴注入
服務是實現專一目的的邏輯單元, 如:日誌服務。
示例:
export class LoggerService {
constructor() {}
debug(msg: string) {
console.log(msg);
}
error(msg: string) {
console.error(msg);
}
}
依賴注入
依賴注入是元件引入外部構建(如:服務)的一種機制。
// 裝飾器
@Component({
selector: 'hello',
template: '<p>{{greeting}}</p>',
providers: [LoggerService]
})
// 元件類
export class HelloComponent {
private greeting: string;
constructor(logger: LoggerService) {
this.greeting = 'Hello, Angular 2!';
logger.debug('建構函式執行完畢');
}
}
分層注入
注入 -> 重新注入
2-4 模組
模組由元件、指令、服務組成。
檔案模組
- 核心模組:@angular/core
- 通用模組:@angular/common
- 表單模組:@angular/forms
- 網路模組:@angular/http
檔案模組使用示例
import { http } from "@angular/http"
// @Component裝飾器
import { Component } from "@angular/core"
// @Directive裝飾器
import { Directive } from "@angular/core"
import { ElementRef, Renderer} from "@angular/core"
應用模組
@NgModule({
declarations: [
AppComponent,
SomeDirective
],
providers: [ LoggerService ],
imports: [ OtherModule ],
bootstrap: [ AppComponent ],
exports: [ SomeDirective ]
})
export class AppModule {}
- declarations: 包裝元件或指令等
- providers: 依賴注入
- imports: 匯入其他模組
- bootstrap: 設定根元件
- exports: 匯出元件或指令等