- 安裝 Nodejs and npm
- https://nodejs.org/en/download/
- 版本需求: node 6.9.x and npm 3.x.x 以上
- Angular Cli
npm install -g @angular/cli
到這裡就已經完成準備了
要建立新專案很簡單,只要直接用 ng 指令即可
ng new my-app
接著進入這個 folder 底下執行,第一個 Hello World 就完成了 此時會預設開啟 http://localhost:4200/
cd my-app
ng serve --o
- 這裡參數 --o 代表自動開啟瀏覽器,也可以使用 --open
主要的檔案都放在 src 底下,包含 主頁面 index.html
app/ 有著所有 ts / html / css 檔案以及 build 完的 .js 都會在這裡面
Angular 主要是利用 component 概念來互相加疊成最後 UI 的長相
在主頁面 index.html 頁面下,有一個 app-root
的 tag,這個會是整個 UI 的 root,而對應的 bootstrap: app.component 則是負責這個 app-root 的長相。
我們將會在 app.component 定義 UI 的長相,並且將他在 module 中 declarations 並且設定為 bootstrap (入口點)
每一隻 app 都有一個 root module: AppModule,我們會將它定義在 app.modules.ts
app.modules.ts
/* app.modules.ts */
// import 這隻 webapp 會用到的 package,最基本的 BrowserModule 和 NgModule
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
// 入口點的 component 也要 import 進來
import {AppComponent} from './app.component';
// 定義這個 module 的 metadata
@NgModule({
declarations: [AppComponent], // 宣告這個 app 的 component
imports: [BrowserModule], // 要使用到的 package
bootstrap: [AppComponent] // 表示這個 webapp 的入口點
})
export class AppModule {}
- BrowserModule 是每個 application 都必須要用到的 service providers,它包含了很多 Angular 的基本運用,像是: NgIf and NgFor
webapp 的 root component - AppComponent
在這個 component 之中定義了基本的三項
- selector: 目標的 tag
- template: component 的長相
- styles: component 的 style
我們要在這裡描述 index.html 之中 my-app tag 的長相
/* app.component.ts */
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>{{title}}</h1>`,
styles: [`h1 { font-weight: normal; }`]
})
export class AppComponent {
title = 'Hello World';
}
當一個 component 越來越大的時候,把 template & styles 分開,寫作與維護上會更清楚,因此把 AppComponent 改寫成下面三個檔案:
/* app.component.ts */
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
})
export class AppComponent {
title = 'Hello World';
}
<!-- app.component.html -->
<h1>{{title}}</h1>
/* app.component.css */
h1 { font-weight: normal; }