# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。