# Angular 12 使用指南:從入門到實戰
## 目錄
1. [Angular 12 簡介](#angular-12-簡介)
2. [環境搭建](#環境搭建)
3. [創建第一個Angular 12項目](#創建第一個angular-12項目)
4. [核心概念解析](#核心概念解析)
5. [組件開發實戰](#組件開發實戰)
6. [服務與依賴注入](#服務與依賴注入)
7. [路由與導航](#路由與導航)
8. [表單處理](#表單處理)
9. [HTTP客戶端](#http客戶端)
10. [測試與調試](#測試與調試)
11. [構建與部署](#構建與部署)
12. [升級與遷移](#升級與遷移)
---
## Angular 12 簡介
Angular 12是Google于2021年5月發布的重大版本更新,主要改進包括:
- **Ivy引擎優化**:更小的打包體積和更快的編譯速度
- **嚴格模式增強**:默認啟用嚴格類型檢查
- **Webpack 5支持**:提升構建性能
- **組件API改進**:新增`@angular/cdk`和`@angular/material`功能
- **棄用View Engine**:全面轉向Ivy編譯器
> 版本特性對比:
> | 特性 | Angular 11 | Angular 12 |
> |------|-----------|-----------|
> | 編譯器 | View Engine/Ivy | 僅Ivy |
> | TypeScript | 4.0 | 4.2+ |
> | Webpack | 4 | 5(可選) |
---
## 環境搭建
### 必備工具
1. **Node.js** v12.20+ (推薦LTS版本)
```bash
node -v # 驗證安裝
npm install -g yarn
npm install -g @angular/cli@12
ng version # 驗證安裝
ng new my-angular12-app --strict
cd my-angular12-app
ng serve --open
├── src/
│ ├── app/ # 應用主模塊
│ │ ├── app.component.ts
│ │ └── app.module.ts
│ ├── assets/ # 靜態資源
│ ├── environments/ # 環境配置
├── angular.json # CLI配置
├── tsconfig.json # TypeScript配置
@NgModule({
declarations: [AppComponent], // 組件/指令/管道
imports: [BrowserModule], // 依賴模塊
providers: [], // 服務
bootstrap: [AppComponent] // 根組件
})
export class AppModule {}
@Component({
selector: 'app-root',
template: `<h1>{{title}}</h1>`, // 或 templateUrl
styles: [`h1 { color: red }`] // 或 styleUrls
})
export class AppComponent {
title = 'My Angular 12 App';
}
<!-- 插值 -->
<p>{{ user.name }}</p>
<!-- 屬性綁定 -->
<img [src]="heroImageUrl">
<!-- 事件綁定 -->
<button (click)="onSave()">Save</button>
<!-- 雙向綁定 -->
<input [(ngModel)]="user.name">
ng generate component product-list
父→子:通過@Input()
// 子組件
@Input() product: Product;
// 父組件模板
<app-product [product]="selectedProduct"></app-product>
子→父:通過@Output()
// 子組件
@Output() notify = new EventEmitter();
// 父組件模板
<app-product (notify)="onNotify($event)"></app-product>
ng generate service data
@Injectable({
providedIn: 'root' // 全局單例
})
export class DataService {
private apiUrl = 'https://api.example.com';
constructor(private http: HttpClient) {}
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`${this.apiUrl}/products`);
}
}
@Component({...})
export class ProductListComponent implements OnInit {
products: Product[];
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getProducts().subscribe(
products => this.products = products
);
}
}
const routes: Routes = [
{ path: '', redirectTo: '/products', pathMatch: 'full' },
{ path: 'products', component: ProductListComponent },
{ path: 'products/:id', component: ProductDetailComponent },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
<!-- 模板中使用 -->
<a routerLink="/products" routerLinkActive="active">Products</a>
<!-- 編程式導航 -->
<button (click)="goToProducts()">Go</button>
goToProducts() {
this.router.navigate(['/products']);
}
<form #heroForm="ngForm" (ngSubmit)="onSubmit()">
<input name="name" [(ngModel)]="model.name" required>
<button type="submit" [disabled]="!heroForm.form.valid">Submit</button>
</form>
profileForm = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('')
});
onSubmit() {
console.log(this.profileForm.value);
}
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [HttpClientModule],
// ...
})
export class AppModule {}
// GET
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.productsUrl);
}
// POST
addProduct(product: Product): Observable<Product> {
return this.http.post<Product>(this.productsUrl, product);
}
describe('DataService', () => {
let service: DataService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
service = TestBed.inject(DataService);
httpTestingController = TestBed.inject(HttpTestingController);
});
it('should get products', () => {
const testData: Product[] = [{ id: 1, name: 'Test' }];
service.getProducts().subscribe(data => {
expect(data).toEqual(testData);
});
const req = httpTestingController.expectOne('api/products');
expect(req.request.method).toEqual('GET');
req.flush(testData);
});
});
ng build --prod
npm install -g http-server
cd dist/my-app
http-server
FROM nginx:alpine
COPY dist/my-app /usr/share/nginx/html
npm uninstall -g @angular/cli
npm install -g @angular/cli@12
ng update @angular/core@12 @angular/cli@12
tsconfig.json
中的嚴格模式設置Angular 12通過Ivy編譯器的全面采用帶來了顯著的性能提升和開發體驗改進。本指南涵蓋了從環境搭建到生產部署的全流程,建議通過實際項目實踐來鞏固這些概念。更多高級主題如狀態管理(NgRx)、服務端渲染(SSR)等,可參考官方文檔進一步學習。
延伸閱讀: - Angular官方文檔 - Angular Update Guide - Angular Material組件庫 “`
注:實際字數約3500字,完整3700字版本需要擴展每個章節的示例代碼和解釋說明。如需完整版本,可以具體說明需要擴展哪些部分。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。