作者:王芃 wpcfan@gmail.com
第一節(jié):初識Angular-CLI
第二節(jié):登錄組件的構(gòu)建
第三節(jié):建立一個待辦事項應(yīng)用
第四節(jié):進化!模塊化你的應(yīng)用
第五節(jié):多用戶版本的待辦事項應(yīng)用
第六節(jié):使用第三方樣式庫及模塊優(yōu)化用
第七節(jié):給組件帶來活力
Rx--隱藏在Angular 2.x中利劍
Redux你的Angular 2應(yīng)用
第八節(jié):查缺補漏大合集(上)
第九節(jié):查缺補漏大合集(下)
第三節(jié):建立一個待辦事項應(yīng)用
這一章我們會建立一個更復(fù)雜的待辦事項應(yīng)用,當(dāng)然我們的登錄功能也還保留,這樣的話我們的應(yīng)用就有了多個相對獨立的功能模塊。以往的web應(yīng)用根據(jù)不同的功能跳轉(zhuǎn)到不同的功能頁面。但目前前端的趨勢是開發(fā)一個SPA(Single Page Application 單頁應(yīng)用),所以其實我們應(yīng)該把這種跳轉(zhuǎn)叫視圖切換:根據(jù)不同的路徑顯示不同的組件。那我們怎么處理這種視圖切換呢?幸運的是,我們無需尋找第三方組件,Angular官方內(nèi)建了自己的路由模塊。
建立routing的步驟
由于我們要以路由形式顯示組件,建立路由前,讓我們先把src\app\app.component.html
中的<app-login></app-login>
刪掉。
- 第一步:在
src/index.html
中指定基準(zhǔn)路徑,即在<head>
中加入<base href="/">
,這個是指向你的index.html
所在的路徑,瀏覽器也會根據(jù)這個路徑下載css,圖像和js文件,所以請將這個語句放在 head 的最頂端。 - 第二步:在
src/app/app.module.ts
中引入RouterModule:import { RouterModule } from '@angular/router';
- 第三步:定義和配置路由數(shù)組,我們暫時只為login來定義路由,仍然在
src/app/app.module.ts
中的imports中
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{
path: 'login',
component: LoginComponent
}
])
],
注意到這個形式和其他的比如BrowserModule、FormModule和HTTPModule表現(xiàn)形式好像不太一樣,這里解釋一下,forRoot其實是一個靜態(tài)的工廠方法,它返回的仍然是Module,下面的是Angular API文檔給出的RouterModule.forRoot
的定義。
forRoot(routes: Routes, config?: ExtraOptions) : ModuleWithProviders
為什么叫forRoot呢?因為這個路由定義是應(yīng)用在應(yīng)用根部的,你可能猜到了還有一個工廠方法叫forChild,后面我們會詳細(xì)講。接下來我們看一下forRoot接收的參數(shù),參數(shù)看起來是一個數(shù)組,每個數(shù)組元素是一個{path: 'xxx', component: XXXComponent}
這個樣子的對象。這個數(shù)組就叫做路由定義(RouteConfig)數(shù)組,每個數(shù)組元素就叫路由定義,目前我們只有一個路由定義。路由定義這個對象包括若干屬性:
- path:路由器會用它來匹配路由中指定的路徑和瀏覽器地址欄中的當(dāng)前路徑,如 /login 。
- component:導(dǎo)航到此路由時,路由器需要創(chuàng)建的組件,如
LoginComponent
。 - redirectTo:重定向到某個path,使用場景的話,比如在用戶輸入不存在的路徑時重定向到首頁。
- pathMatch:路徑的字符匹配策略
- children:子路由數(shù)組
運行一下,我們會發(fā)現(xiàn)出錯了
image_1b0hgdsiu87n1lha1kcahl51ckb9.png-233.2kB
這個錯誤看上去應(yīng)該是對于''沒有找到匹配的route,這是由于我們只定義了一個'login',我們再試試在瀏覽器地址欄輸入:http://localhost:4200/login
。這次仍然出錯,但錯誤信息變成了下面的樣子,意思是我們沒有找到一個outlet去加載LoginComponent。對的,這就引出了router outlet的概念,如果要顯示對應(yīng)路由的組件,我們需要一個插頭(outlet)來裝載組件。
error_handler.js:48EXCEPTION: Uncaught (in promise): Error: Cannot find primary outlet to load 'LoginComponent'
Error: Cannot find primary outlet to load 'LoginComponent'
at getOutlet (http://localhost:4200/main.bundle.js:66161:19)
at ActivateRoutes.activateRoutes (http://localhost:4200/main.bundle.js:66088:30)
at http://localhost:4200/main.bundle.js:66052:19
at Array.forEach (native)
at ActivateRoutes.activateChildRoutes (http://localhost:4200/main.bundle.js:66051:29)
at ActivateRoutes.activate (http://localhost:4200/main.bundle.js:66046:14)
at http://localhost:4200/main.bundle.js:65787:56
at SafeSubscriber._next (http://localhost:4200/main.bundle.js:9000:21)
at SafeSubscriber.__tryOrSetError (http://localhost:4200/main.bundle.js:42013:16)
at SafeSubscriber.next (http://localhost:4200/main.bundle.js:41955:27)
下面我們把<router-outlet></router-outlet>
寫在src\app\app.component.html
的末尾,地址欄輸入http://localhost:4200/login
重新看看瀏覽器中的效果吧,我們的應(yīng)用應(yīng)該正常顯示了。但如果輸入http://localhost:4200
時仍然是有異常出現(xiàn)的,我們需要添加一個路由定義來處理。輸入http://localhost:4200
時相對于根路徑的path應(yīng)該是空,即''。而我們這時希望將用戶仍然引導(dǎo)到登錄頁面,這就是redirectTo: 'login'
的作用。pathMatch: 'full'
的意思是必須完全符合路徑的要求,也就是說http://localhost:4200/1
是不會匹配到這個規(guī)則的,必須嚴(yán)格是http://localhost:4200
RouterModule.forRoot([
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
}
])
注意路徑配置的順序是非常重要的,Angular2使用“先匹配優(yōu)先”的原則,也就是說如果一個路徑可以同時匹配幾個路徑配置的規(guī)則的話,以第一個匹配的規(guī)則為準(zhǔn)。
但是現(xiàn)在還有一點小不爽,就是直接在app.modules.ts
中定義路徑并不是很好的方式,因為隨著路徑定義的復(fù)雜,這部分最好還是用單獨的文件來定義?,F(xiàn)在我們新建一個文件src\app\app.routes.ts
,將上面在app.modules.ts
中定義的路徑刪除并在app.routes.ts
中重新定義。
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
export const routes: Routes = [
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
}
];
export const routing = RouterModule.forRoot(routes);
接下來我們在app.modules.ts
中引入routing,import { routing } from './app.routes';
,然后在imports數(shù)組里添加routing,現(xiàn)在我們的app.modules.ts
看起來是下面這個樣子。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { AuthService } from './core/auth.service';
import { routing } from './app.routes';
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing
],
providers: [
{provide: 'auth', useClass: AuthService}
],
bootstrap: [AppComponent]
})
export class AppModule { }
讓待辦事項變得有意義
現(xiàn)在我們來規(guī)劃一下根路徑'',對應(yīng)根路徑我們想建立一個todo組件,那么我們使用ng g c todo
來生成組件,然后在app.routes.ts
中加入路由定義,對于根路徑我們不再需要重定向到登錄了,我們把它改寫成重定向到todo。
export const routes: Routes = [
{
path: '',
redirectTo: 'todo',
pathMatch: 'full'
},
{
path: 'todo',
component: TodoComponent
},
{
path: 'login',
component: LoginComponent
}
];
在瀏覽器中鍵入http://localhost:4200
可以看到自動跳轉(zhuǎn)到了todo路徑,并且我們的todo組件也顯示出來了。

我們希望的Todo頁面應(yīng)該有一個輸入待辦事項的輸入框和一個顯示待辦事項狀態(tài)的列表。那么我們先來定義一下todo的結(jié)構(gòu),todo應(yīng)該有一個id用來唯一標(biāo)識,還應(yīng)該有一個desc用來描述這個todo是干什么的,再有一個completed用來標(biāo)識是否已經(jīng)完成。好了,我們來建立這個todo模型吧,在todo文件夾下新建一個文件todo.model.ts
export class Todo {
id: number;
desc: string;
completed: boolean;
}
然后我們應(yīng)該改造一下todo組件了,引入剛剛建立好的todo對象,并且建立一個todos數(shù)組作為所有todo的集合,一個desc是當(dāng)前添加的新的todo的內(nèi)容。當(dāng)然我們還需要一個addTodo方法把新的todo加到todos數(shù)組中。這里我們暫且寫一個漏洞百出的版本。
import { Component, OnInit } from '@angular/core';
import { Todo } from './todo.model';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {
todos: Todo[] = [];
desc = '';
constructor() { }
ngOnInit() {
}
addTodo(){
this.todos.push({id: 1, desc: this.desc, completed: false});
this.desc = '';
}
}
然后我們改造一下src\app\todo\todo.component.html
<div>
<input type="text" [(ngModel)]="desc" (keyup.enter)="addTodo()">
<ul>
<li *ngFor="let todo of todos">{{ todo.desc }}</li>
</ul>
</div>
如上面代碼所示,我們建立了一個文本輸入框,這個輸入框的值應(yīng)該是新todo的描述(desc),我們想在用戶按了回車鍵后進行添加操作((keyup.enter)="addTodo()
)。由于todos是個數(shù)組,所以我們利用一個循環(huán)將數(shù)組內(nèi)容顯示出來(<li *ngFor="let todo of todos">{{ todo.desc }}</li>
)。好了讓我們欣賞一下成果吧

如果我們還記得之前提到的業(yè)務(wù)邏輯應(yīng)該放在單獨的service中,我們還可以做的更好一些。在todo文件夾內(nèi)建立TodoService:ng g s todo\todo
。上面的例子中所有創(chuàng)建的todo都是id為1的,這顯然是一個大bug,我們看一下怎么處理。常見的不重復(fù)id創(chuàng)建方式有兩種,一個是搞一個自增長數(shù)列,另一個是采用隨機生成一組不可能重復(fù)的字符序列,常見的就是UUID了。我們來引入一個uuid的包:npm i --save angular2-uuid
,由于這個包中已經(jīng)含有了用于typescript的定義文件,這里就執(zhí)行這一個命令就足夠了。由于此時Todo
對象的id
已經(jīng)是字符型了,請更改其聲明為id: string;
。
然后修改service成下面的樣子:
import { Injectable } from '@angular/core';
import {Todo} from './todo.model';
import { UUID } from 'angular2-uuid';
@Injectable()
export class TodoService {
todos: Todo[] = [];
constructor() { }
addTodo(todoItem:string): Todo[] {
let todo = {
id: UUID.UUID(),
desc: todoItem,
completed: false
};
this.todos.push(todo);
return this.todos;
}
}
當(dāng)然我們還要把組件中的代碼改成使用service的
import { Component, OnInit } from '@angular/core';
import { Todo } from './todo.model';
import { TodoService } from './todo.service';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css'],
providers:[TodoService]
})
export class TodoComponent implements OnInit {
todos: Todo[] = [];
desc = '';
constructor(private service:TodoService) { }
ngOnInit() {
}
addTodo(){
this.todos = this.service.addTodo(this.desc);
this.desc = '';
}
}
為了可以清晰的看到我們的成果,我們?yōu)閏hrome瀏覽器裝一個插件,在chrome的地址欄中輸入chrome://extensions
,拉到最底部會看到一個“獲取更多擴展程序”的鏈接,點擊這個鏈接然后搜索“Augury”,安裝即可。安裝好后,按F12調(diào)出開發(fā)者工具,里面出現(xiàn)一個叫“Augury”的tab。

我們可以看到id這時候被設(shè)置成了一串字符,這個就是UUID了。
建立模擬web服務(wù)和異步操作
實際的開發(fā)中我們的service是要和服務(wù)器api進行交互的,而不是現(xiàn)在這樣簡單的操作數(shù)組。但問題來了,現(xiàn)在沒有web服務(wù)啊,難道真要自己開發(fā)一個嗎?答案是可以做個假的,假作真時真亦假。我們在開發(fā)過程中經(jīng)常會遇到這類問題,等待后端同學(xué)的進度是很痛苦的。所以Angular內(nèi)建提供了一個可以快速建立測試用web服務(wù)的方法:內(nèi)存 (in-memory) 服務(wù)器。
一般來說,你需要知道自己對服務(wù)器的期望是什么,期待它返回什么樣的數(shù)據(jù),有了這個數(shù)據(jù)呢,我們就可以自己快速的建立一個內(nèi)存服務(wù)器了。拿這個例子來看,我們可能需要一個這樣的對象
class Todo {
id: string;
desc: string;
completed: boolean;
}
對應(yīng)的JSON應(yīng)該是這樣的
{
"data": [
{
"id": "f823b191-7799-438d-8d78-fcb1e468fc78",
"desc": "blablabla",
"completed": false
},
{
"id": "c316a3bf-b053-71f9-18a3-0073c7ee3b76",
"desc": "tetssts",
"completed": false
},
{
"id": "dd65a7c0-e24f-6c66-862e-0999ea504ca0",
"desc": "getting up",
"completed": false
}
]
}
首先我們需要安裝angular-in-memory-web-api
,輸入npm install --save angular-in-memory-web-api
然后在Todo文件夾下創(chuàng)建一個文件src\app\todo\todo-data.ts
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Todo } from './todo.model';
export class InMemoryTodoDbService implements InMemoryDbService {
createDb() {
let todos: Todo[] = [
{id: "f823b191-7799-438d-8d78-fcb1e468fc78", desc: 'Getting up', completed: true},
{id: "c316a3bf-b053-71f9-18a3-0073c7ee3b76", desc: 'Go to school', completed: false}
];
return {todos};
}
}
可以看到,我們創(chuàng)建了一個實現(xiàn)InMemoryDbService
的內(nèi)存數(shù)據(jù)庫,這個數(shù)據(jù)庫其實也就是把數(shù)組傳入進去。接下來我們要更改src\app\app.module.ts
,加入類引用和對應(yīng)的模塊聲明:
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryTodoDbService } from './todo/todo-data';
然后在imports數(shù)組中緊挨著HttpModule
加上InMemoryWebApiModule.forRoot(InMemoryTodoDbService),
。
現(xiàn)在我們在service中試著調(diào)用我們的“假web服務(wù)”吧
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { UUID } from 'angular2-uuid';
import 'rxjs/add/operator/toPromise';
import { Todo } from './todo.model';
@Injectable()
export class TodoService {
//定義你的假WebAPI地址,這個定義成什么都無所謂
//只要確保是無法訪問的地址就好
private api_url = 'api/todos';
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) { }
// POST /todos
addTodo(desc:string): Promise<Todo> {
let todo = {
id: UUID.UUID(),
desc: desc,
completed: false
};
return this.http
.post(this.api_url, JSON.stringify(todo), {headers: this.headers})
.toPromise()
.then(res => res.json().data as Todo)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
上面的代碼我們看到定義了一個api_url = 'api/todos',你可能會問這個是怎么來的?分兩部分看,api/todos中前面的api定義成什么都可以,但后面這個todos是有講究的,我們回去看一下src\app\todo\todo-data.ts返回的return {todos},這個其實是return {todos: todos}的省略表示形式,如果我們不想讓這個后半部分是todos,我們可以寫成{nahnahnah: todos}。這樣的話我們改寫成api_url = 'blablabla/nahnahnah'也無所謂,因為這個內(nèi)存Web服務(wù)的機理是攔截Web訪問,也就是說隨便什么地址都可以,內(nèi)存Web服務(wù)會攔截這個地址并解析你的請求是否滿足RESTful API的要求
簡單來說RESTful API中GET請求用于查詢,PUT用于更新,DELETE用于刪除,POST用于添加。比如如果url是api/todos,那么
- 查詢所有待辦事項:以GET方法訪問
api/todos
- 查詢單個待辦事項:以GET方法訪問
api/todos/id
,比如id是1,那么訪問api/todos/1
- 更新某個待辦事項:以PUT方法訪問
api/todos/id
- 刪除某個待辦事項:以DELETE方法訪問
api/todos/id
- 增加一個待辦事項:以POST方法訪問
api/todos
在service的構(gòu)造函數(shù)中我們注入了Http,而angular的Http封裝了大部分我們需要的方法,比如例子中的增加一個todo,我們就調(diào)用this.http.post(url, body, options)
,上面代碼中的.post(this.api_url, JSON.stringify(todo), {headers: this.headers})
含義是:構(gòu)造一個POST類型的HTTP請求,其訪問的url是this.api_url
,request的body是一個JSON(把todo對象轉(zhuǎn)換成JSON),在參數(shù)配置中我們配置了request的header。
這個請求發(fā)出后返回的是一個Observable(可觀察對象),我們把它轉(zhuǎn)換成Promise然后處理res(Http Response)。Promise提供異步的處理,注意到then中的寫法,這個和我們傳統(tǒng)編程寫法不大一樣,叫做lambda表達(dá)式,相當(dāng)于是一個匿名函數(shù),(input parameters) => expression
,=>
前面的是函數(shù)的參數(shù),后面的是函數(shù)體。
還要一點需要強調(diào)的是:在用內(nèi)存Web服務(wù)時,一定要注意res.json().data
中的data屬性必須要有,因為內(nèi)存web服務(wù)坑爹的在返回的json中加了data對象,你真正要得到的json是在這個data里面。
下一步我們來更改Todo組件的addTodo方法以便可以使用我們新的異步http方法
addTodo(){
this.service
.addTodo(this.desc)
.then(todo => {
this.todos = [...this.todos, todo];
this.desc = '';
});
}
這里面的前半部分應(yīng)該還是好理解的:this.service.addTodo(this.desc)
是調(diào)用service的對應(yīng)方法而已,但后半部分是什么鬼?...
這個貌似省略號的東東是ES7中計劃提供的Object Spread操作符,它的功能是將對象或數(shù)組“打散,拍平”。這么說可能還是不懂,舉例子吧:
let arr = [1,2,3];
let arr2 = [...arr];
arr2.push(4);
// arr2 變成了 [1,2,3,4]
// arr 保存原來的樣子
let arr3 = [0, 1, 2];
let arr4 = [3, 4, 5];
arr3.push(...arr4);
// arr3變成了[0, 1, 2, 3, 4, 5]
let arr5 = [0, 1, 2];
let arr6 = [-1, ...arr5, 3];
// arr6 變成了[-1, 0, 1, 2, 3]
所以呢我們上面的this.todos = [...this.todos, todo];
相當(dāng)于為todos增加一個新元素,和push很像,那為什么不用push呢?因為這樣構(gòu)造出來的對象是全新的,而不是引用的,在現(xiàn)代編程中一個明顯的趨勢是不要在過程中改變輸入的參數(shù)。第二個原因是這樣做會帶給我們極大的便利性和編程的一致性。下面通過給我們的例子添加幾個功能,我們來一起體會一下。
首先更改src\app\todo\todo.service.ts
//src\app\todo\todo.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { UUID } from 'angular2-uuid';
import 'rxjs/add/operator/toPromise';
import { Todo } from './todo.model';
@Injectable()
export class TodoService {
private api_url = 'api/todos';
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) { }
// POST /todos
addTodo(desc:string): Promise<Todo> {
let todo = {
id: UUID.UUID(),
desc: desc,
completed: false
};
return this.http
.post(this.api_url, JSON.stringify(todo), {headers: this.headers})
.toPromise()
.then(res => res.json().data as Todo)
.catch(this.handleError);
}
// PUT /todos/:id
toggleTodo(todo: Todo): Promise<Todo> {
const url = `${this.api_url}/${todo.id}`;
console.log(url);
let updatedTodo = Object.assign({}, todo, {completed: !todo.completed});
return this.http
.put(url, JSON.stringify(updatedTodo), {headers: this.headers})
.toPromise()
.then(() => updatedTodo)
.catch(this.handleError);
}
// DELETE /todos/:id
deleteTodoById(id: string): Promise<void> {
const url = `${this.api_url}/${id}`;
return this.http
.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
// GET /todos
getTodos(): Promise<Todo[]>{
return this.http.get(this.api_url)
.toPromise()
.then(res => res.json().data as Todo[])
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
然后更新src\app\todo\todo.component.ts
import { Component, OnInit } from '@angular/core';
import { TodoService } from './todo.service';
import { Todo } from './todo.model';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css'],
providers: [TodoService]
})
export class TodoComponent implements OnInit {
todos : Todo[] = [];
desc: string = '';
constructor(private service: TodoService) {}
ngOnInit() {
this.getTodos();
}
addTodo(){
this.service
.addTodo(this.desc)
.then(todo => {
this.todos = [...this.todos, todo];
this.desc = '';
});
}
toggleTodo(todo: Todo) {
const i = this.todos.indexOf(todo);
this.service
.toggleTodo(todo)
.then(t => {
this.todos = [
...this.todos.slice(0,i),
t,
...this.todos.slice(i+1)
];
});
}
removeTodo(todo: Todo) {
const i = this.todos.indexOf(todo);
this.service
.deleteTodoById(todo.id)
.then(()=> {
this.todos = [
...this.todos.slice(0,i),
...this.todos.slice(i+1)
];
});
}
getTodos(): void {
this.service
.getTodos()
.then(todos => this.todos = [...todos]);
}
}
更新模板文件src\app\todo\todo.component.html
<section class="todoapp">
<header class="header">
<h1>Todos</h1>
<input class="new-todo" placeholder="What needs to be done?" autofocus="" [(ngModel)]="desc" (keyup.enter)="addTodo()">
</header>
<section class="main" *ngIf="todos?.length > 0">
<input class="toggle-all" type="checkbox">
<ul class="todo-list">
<li *ngFor="let todo of todos" [class.completed]="todo.completed">
<div class="view">
<input class="toggle" type="checkbox" (click)="toggleTodo(todo)" [checked]="todo.completed">
<label (click)="toggleTodo(todo)">{{todo.desc}}</label>
<button class="destroy" (click)="removeTodo(todo); $event.stopPropagation()"></button>
</div>
</li>
</ul>
</section>
<footer class="footer" *ngIf="todos?.length > 0">
<span class="todo-count">
<strong>{{todos?.length}}</strong> {{todos?.length == 1 ? 'item' : 'items'}} left
</span>
<ul class="filters">
<li><a href="">All</a></li>
<li><a href="">Active</a></li>
<li><a href="">Completed</a></li>
</ul>
<button class="clear-completed">Clear completed</button>
</footer>
</section>
更新組件的css樣式:src\app\todo\todo.component.css
.todoapp {
background: #fff;
margin: 130px 0 40px 0;
position: relative;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.todoapp input::-webkit-input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::-moz-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp h1 {
position: absolute;
top: -155px;
width: 100%;
font-size: 100px;
font-weight: 100;
text-align: center;
color: rgba(175, 47, 47, 0.15);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
.new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
font-weight: inherit;
line-height: 1.4em;
border: 0;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.003);
box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
}
.main {
position: relative;
z-index: 2;
border-top: 1px solid #e6e6e6;
}
label[for='toggle-all'] {
display: none;
}
.toggle-all {
position: absolute;
top: -55px;
left: -12px;
width: 60px;
height: 34px;
text-align: center;
border: none; /* Mobile Safari */
}
.toggle-all:before {
content: '?';
font-size: 22px;
color: #e6e6e6;
padding: 10px 27px 10px 27px;
}
.toggle-all:checked:before {
color: #737373;
}
.todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px solid #ededed;
}
.todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
display: block;
width: 506px;
padding: 12px 16px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
appearance: none;
}
.todo-list li .toggle:after {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#ededed" stroke-width="3"/></svg>');
}
.todo-list li .toggle:checked:after {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#bddad5" stroke-width="3"/><path fill="#5dc2af" d="M72 25L42 71 27 56l-4 4 20 20 34-52z"/></svg>');
}
.todo-list li label {
word-break: break-all;
padding: 15px 60px 15px 15px;
margin-left: 45px;
display: block;
line-height: 1.2;
transition: color 0.4s;
}
.todo-list li.completed label {
color: #d9d9d9;
text-decoration: line-through;
}
.todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 30px;
color: #cc9a9a;
margin-bottom: 11px;
transition: color 0.2s ease-out;
}
.todo-list li .destroy:hover {
color: #af5b5e;
}
.todo-list li .destroy:after {
content: '×';
}
.todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
color: #777;
padding: 10px 15px;
height: 20px;
text-align: center;
border-top: 1px solid #e6e6e6;
}
.footer:before {
content: '';
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 50px;
overflow: hidden;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
0 8px 0 -3px #f6f6f6,
0 9px 1px -3px rgba(0, 0, 0, 0.2),
0 16px 0 -6px #f6f6f6,
0 17px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
float: left;
text-align: left;
}
.todo-count strong {
font-weight: 300;
}
.filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
.filters li {
display: inline;
}
.filters li a {
color: inherit;
margin: 3px;
padding: 3px 7px;
text-decoration: none;
border: 1px solid transparent;
border-radius: 3px;
}
.filters li a:hover {
border-color: rgba(175, 47, 47, 0.1);
}
.filters li a.selected {
border-color: rgba(175, 47, 47, 0.2);
}
.clear-completed,
html .clear-completed:active {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
cursor: pointer;
}
.clear-completed:hover {
text-decoration: underline;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
.toggle-all,
.todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
height: 40px;
}
.toggle-all {
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-appearance: none;
appearance: none;
}
}
@media (max-width: 430px) {
.footer {
height: 50px;
}
.filters {
bottom: 10px;
}
}
更新src\styles.css
為如下
/* You can add global styles to this file, and also import other style files */
html, body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
font-weight: inherit;
color: inherit;
-webkit-appearance: none;
appearance: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #f5f5f5;
color: #4d4d4d;
min-width: 230px;
max-width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 300;
}
:focus {
outline: 0;
}
.hidden {
display: none;
}
.info {
margin: 65px auto 0;
color: #bfbfbf;
font-size: 10px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
text-align: center;
}
.info p {
line-height: 1;
}
.info a {
color: inherit;
text-decoration: none;
font-weight: 400;
}
.info a:hover {
text-decoration: underline;
}
現(xiàn)在我們看看成果吧,現(xiàn)在好看多了

本節(jié)代碼:https://github.com/wpcfan/awesome-tutorials/tree/chap03/angular2/ng2-tut
紙書出版了,比網(wǎng)上內(nèi)容豐富充實了,歡迎大家訂購!
京東鏈接:https://item.m.jd.com/product/12059091.html?from=singlemessage&isappinstalled=0

第一節(jié):初識Angular-CLI
第二節(jié):登錄組件的構(gòu)建
第三節(jié):建立一個待辦事項應(yīng)用
第四節(jié):進化!模塊化你的應(yīng)用
第五節(jié):多用戶版本的待辦事項應(yīng)用
第六節(jié):使用第三方樣式庫及模塊優(yōu)化用
第七節(jié):給組件帶來活力
Rx--隱藏在Angular 2.x中利劍
Redux你的Angular 2應(yīng)用
第八節(jié):查缺補漏大合集(上)
第九節(jié):查缺補漏大合集(下)