Angular 的 Scaffolding 主要是透過 CLI 達成的
Angular 至少需要一個 Component 跟一個 Module 才能運作
一開始的那個 Component 被定義在 app.component.ts
檔案雖然說那樣命名,稱呼上是叫它AppComponent
它是所有 Component 的根,其他的 Component 或是一般的 HTML 都可以從這一層層往下長
可以把它想像成樂高底下那個綠色的平臺,Component 從不同的 Module 取出後都是組在它上面
這個檔案的內容長得如下:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
}
這裡定義了一個類別
<h1>
{{ title }}
</h1>
一開始的 Module 被定義在 app.module.ts
它的內容如下:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Bootstrapping
開始渲染的流程
Angular CLI 是透過 webpack 處理這塊
我們可以從 angular.json 這個檔案看到建置這個 app 跟一個 main.ts 有關
那 main.ts 裡又是什麼呢?
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
main.ts 的職責就是要 bootstrap 這個 app
11-12 行是真正開始 bootstrap 的程式碼
index.html
<html>
<body>
<app-root></app-root>
</body>
</html>
小結一下