作者:王芃 wpcfan@gmail.com

第一节:Angular 2.0 从0到1 (一)
第二节:Angular 2.0 从0到1 (二)
第三节:Angular 2.0 从0到1 (三)
第四节:Angular 2.0 从0到1 (四)
第五节:Angular 2.0 从0到1 (五)
第六节:Angular 2.0 从0到1 (六)
第七节:Angular 2.0 从0到1 (七)
第八节:Angular 2.0 从0到1 (八)
番外:Angular 2.0 从0到1 Rx—隐藏在Angular 2.x中利剑
番外:Angular 2.0 从0到1 Rx—Redux你的Angular 2应用

第三节:建立一个待办事项应用

这一章我们会建立一个更复杂的待办事项应用,当然我们的登录功能也还保留,这样的话我们的应用就有了多个相对独立的功能模块。以往的web应用根据不同的功能跳转到不同的功能页面。但目前前端的趋势是开发一个SPA(Single Page Application 单页应用),所以其实我们应该把这种跳转叫视图切换:根据不同的路径显示不同的组件。那我们怎么处理这种视图切换呢?幸运的是,我们无需寻找第三方组件,Angular官方内建了自己的路由模块。

建立routing的步骤

由于我们要以路由形式显示组件,建立路由前,让我们先把src\app\app.component.html中的<app-login></app-login>删掉。

  • 第一步:在src/index.html中指定基准路径,即在<header>中加入<base href="/">,这个是指向你的index.html所在的路径,浏览器也会根据这个路径下载css,图像和js文件,所以请将这个语句放在header的最顶端。
  • 第二步:在src/app/app.module.ts中引入RouterModule:import { RouterModule } from '@angular/router';
  • 第三步:定义和配置路由数组,我们暂时只为login来定义路由,仍然在src/app/app.module.ts中的imports中

    1. imports: [
    2. BrowserModule,
    3. FormsModule,
    4. HttpModule,
    5. RouterModule.forRoot([
    6. {
    7. path: 'login',
    8. component: LoginComponent
    9. }
    10. ])
    11. ],

    注意到这个形式和其他的比如BrowserModule、FormModule和HTTPModule表现形式好像不太一样,这里解释一下,forRoot其实是一个静态的工厂方法,它返回的仍然是Module,下面的是Angular API文档给出的RouterModule.forRoot的定义。

    1. forRoot(routes: Routes, config?: ExtraOptions) : ModuleWithProviders

    为什么叫forRoot呢?因为这个路由定义是应用在应用根部的,你可能猜到了还有一个工厂方法叫forChild,后面我们会详细讲。接下来我们看一下forRoot接收的参数,参数看起来是一个数组,每个数组元素是一个{path: 'xxx', component: XXXComponent}这个样子的对象。这个数组就叫做路由定义(RouteConfig)数组,每个数组元素就叫路由定义,目前我们只有一个路由定义。路由定义这个对象包括若干属性:

    • path:路由器会用它来匹配路由中指定的路径和浏览器地址栏中的当前路径,如 /login 。
    • component:导航到此路由时,路由器需要创建的组件,如 LoginComponent
    • redirectTo:重定向到某个path,使用场景的话,比如在用户输入不存在的路径时重定向到首页。
    • pathMatch:路径的字符匹配策略
    • children:子路由数组
      运行一下,我们会发现出错了

      这个错误看上去应该是对于’’没有找到匹配的route,这是由于我们只定义了一个’login’,我们再试试在浏览器地址栏输入:http://localhost:4200/login。这次仍然出错,但错误信息变成了下面的样子,意思是我们没有找到一个outlet去加载LoginComponent。对的,这就引出了router outlet的概念,如果要显示对应路由的组件,我们需要一个插头(outlet)来装载组件。
      1. error_handler.js:48EXCEPTION: Uncaught (in promise): Error: Cannot find primary outlet to load 'LoginComponent'
      2. Error: Cannot find primary outlet to load 'LoginComponent'
      3. at getOutlet (http://localhost:4200/main.bundle.js:66161:19)
      4. at ActivateRoutes.activateRoutes (http://localhost:4200/main.bundle.js:66088:30)
      5. at http://localhost:4200/main.bundle.js:66052:19
      6. at Array.forEach (native)
      7. at ActivateRoutes.activateChildRoutes (http://localhost:4200/main.bundle.js:66051:29)
      8. at ActivateRoutes.activate (http://localhost:4200/main.bundle.js:66046:14)
      9. at http://localhost:4200/main.bundle.js:65787:56
      10. at SafeSubscriber._next (http://localhost:4200/main.bundle.js:9000:21)
      11. at SafeSubscriber.__tryOrSetError (http://localhost:4200/main.bundle.js:42013:16)
      12. at SafeSubscriber.next (http://localhost:4200/main.bundle.js:41955:27)

      下面我们把<router-outlet></router-outlet>写在src\app\app.component.html的末尾,地址栏输入http://localhost:4200/login重新看看浏览器中的效果吧,我们的应用应该正常显示了。但如果输入http://localhost:4200时仍然是有异常出现的,我们需要添加一个路由定义来处理。输入http://localhost:4200时相对于根路径的path应该是空,即’’。而我们这时希望将用户仍然引导到登录页面,这就是redirectTo: 'login'的作用。pathMatch: 'full'的意思是必须完全符合路径的要求,也就是说http://localhost:4200/1是不会匹配到这个规则的,必须严格是http://localhost:4200

      1. RouterModule.forRoot([
      2. {
      3. path: '',
      4. redirectTo: 'login',
      5. pathMatch: 'full'
      6. },
      7. {
      8. path: 'login',
      9. component: LoginComponent
      10. }
      11. ])

      注意路径配置的顺序是非常重要的,Angular2使用“先匹配优先”的原则,也就是说如果一个路径可以同时匹配几个路径配置的规则的话,以第一个匹配的规则为准。

但是现在还有一点小不爽,就是直接在app.modules.ts中定义路径并不是很好的方式,因为随着路径定义的复杂,这部分最好还是用单独的文件来定义。现在我们新建一个文件src\app\app.routes.ts,将上面在app.modules.ts中定义的路径删除并在app.routes.ts中重新定义。

  1. import { Routes, RouterModule } from '@angular/router';
  2. import { LoginComponent } from './login/login.component';
  3. export const routes: Routes = [
  4. {
  5. path: '',
  6. redirectTo: 'login',
  7. pathMatch: 'full'
  8. },
  9. {
  10. path: 'login',
  11. component: LoginComponent
  12. }
  13. ];
  14. export const routing = RouterModule.forRoot(routes);

接下来我们在app.modules.ts中引入routing,import { routing } from './app.routes';,然后在imports数组里添加routing,现在我们的app.modules.ts看起来是下面这个样子。

  1. import { BrowserModule } from '@angular/platform-browser';
  2. import { NgModule } from '@angular/core';
  3. import { FormsModule } from '@angular/forms';
  4. import { HttpModule } from '@angular/http';
  5. import { AppComponent } from './app.component';
  6. import { LoginComponent } from './login/login.component';
  7. import { AuthService } from './core/auth.service';
  8. import { routing } from './app.routes';
  9. @NgModule({
  10. declarations: [
  11. AppComponent,
  12. LoginComponent
  13. ],
  14. imports: [
  15. BrowserModule,
  16. FormsModule,
  17. HttpModule,
  18. routing
  19. ],
  20. providers: [
  21. {provide: 'auth', useClass: AuthService}
  22. ],
  23. bootstrap: [AppComponent]
  24. })
  25. export class AppModule { }

让待办事项变得有意义

现在我们来规划一下根路径’’,对应根路径我们想建立一个todo组件,那么我们使用ng g c todo来生成组件,然后在app.routes.ts中加入路由定义,对于根路径我们不再需要重定向到登录了,我们把它改写成重定向到todo。

  1. export const routes: Routes = [
  2. {
  3. path: '',
  4. redirectTo: 'todo',
  5. pathMatch: 'full'
  6. },
  7. {
  8. path: 'todo',
  9. component: TodoComponent
  10. },
  11. {
  12. path: 'login',
  13. component: LoginComponent
  14. }
  15. ];

在浏览器中键入http://localhost:4200可以看到自动跳转到了todo路径,并且我们的todo组件也显示出来了。

我们希望的Todo页面应该有一个输入待办事项的输入框和一个显示待办事项状态的列表。那么我们先来定义一下todo的结构,todo应该有一个id用来唯一标识,还应该有一个desc用来描述这个todo是干什么的,再有一个completed用来标识是否已经完成。好了,我们来建立这个todo模型吧,在todo文件夹下新建一个文件todo.model.ts

  1. export class Todo {
  2. id: number;
  3. desc: string;
  4. completed: boolean;
  5. }

然后我们应该改造一下todo组件了,引入刚刚建立好的todo对象,并且建立一个todos数组作为所有todo的集合,一个desc是当前添加的新的todo的内容。当然我们还需要一个addTodo方法把新的todo加到todos数组中。这里我们暂且写一个漏洞百出的版本。

  1. import { Component, OnInit } from '@angular/core';
  2. import { Todo } from './todo.model';
  3. @Component({
  4. selector: 'app-todo',
  5. templateUrl: './todo.component.html',
  6. styleUrls: ['./todo.component.css']
  7. })
  8. export class TodoComponent implements OnInit {
  9. todos: Todo[] = [];
  10. desc = '';
  11. constructor() { }
  12. ngOnInit() {
  13. }
  14. addTodo(){
  15. this.todos.push({id: 1, desc: this.desc, completed: false});
  16. this.desc = '';
  17. }
  18. }

然后我们改造一下src\app\todo\todo.component.html

  1. <div>
  2. <input type="text" [(ngModel)]="desc" (keyup.enter)="addTodo()">
  3. <ul>
  4. <li *ngFor="let todo of todos">{{ todo.desc }}</li>
  5. </ul>
  6. </div>

如上面代码所示,我们建立了一个文本输入框,这个输入框的值应该是新todo的描述(desc),我们想在用户按了回车键后进行添加操作((keyup.enter)="addTodo())。由于todos是个数组,所以我们利用一个循环将数组内容显示出来(<li *ngFor="let todo of todos">{{ todo.desc }}</li>)。好了让我们欣赏一下成果吧

如果我们还记得之前提到的业务逻辑应该放在单独的service中,我们还可以做的更好一些。在todo文件夹内建立TodoService:ng g s todo\todo。上面的例子中所有创建的todo都是id为1的,这显然是一个大bug,我们看一下怎么处理。常见的不重复id创建方式有两种,一个是搞一个自增长数列,另一个是采用随机生成一组不可能重复的字符序列,常见的就是UUID了。我们来引入一个uuid的包:npm i --save angular2-uuid,由于这个包中已经含有了用于typescript的定义文件,这里就执行这一个命令就足够了。由于此时Todo对象的id已经是字符型了,请更改其声明为id: string;
然后修改service成下面的样子:

  1. import { Injectable } from '@angular/core';
  2. import {Todo} from './todo.model';
  3. import { UUID } from 'angular2-uuid';
  4. @Injectable()
  5. export class TodoService {
  6. todos: Todo[] = [];
  7. constructor() { }
  8. addTodo(todoItem:string): Todo[] {
  9. let todo = {
  10. id: UUID.UUID(),
  11. desc: todoItem,
  12. completed: false
  13. };
  14. this.todos.push(todo);
  15. return this.todos;
  16. }
  17. }

当然我们还要把组件中的代码改成使用service的

  1. import { Component, OnInit } from '@angular/core';
  2. import { Todo } from './todo.model';
  3. import { TodoService } from './todo.service';
  4. @Component({
  5. selector: 'app-todo',
  6. templateUrl: './todo.component.html',
  7. styleUrls: ['./todo.component.css'],
  8. providers:[TodoService]
  9. })
  10. export class TodoComponent implements OnInit {
  11. todos: Todo[] = [];
  12. desc = '';
  13. constructor(private service:TodoService) { }
  14. ngOnInit() {
  15. }
  16. addTodo(){
  17. this.todos = this.service.addTodo(this.desc);
  18. this.desc = '';
  19. }
  20. }

为了可以清晰的看到我们的成果,我们为chrome浏览器装一个插件,在chrome的地址栏中输入chrome://extensions,拉到最底部会看到一个“获取更多扩展程序”的链接,点击这个链接然后搜索“Angury”,安装即可。安装好后,按F12调出开发者工具,里面出现一个叫“Angury”的tab。

我们可以看到id这时候被设置成了一串字符,这个就是UUID了。

建立模拟web服务和异步操作

实际的开发中我们的service是要和服务器api进行交互的,而不是现在这样简单的操作数组。但问题来了,现在没有web服务啊,难道真要自己开发一个吗?答案是可以做个假的,假作真时真亦假。我们在开发过程中经常会遇到这类问题,等待后端同学的进度是很痛苦的。所以Angular内建提供了一个可以快速建立测试用web服务的方法:内存 (in-memory) 服务器。

一般来说,你需要知道自己对服务器的期望是什么,期待它返回什么样的数据,有了这个数据呢,我们就可以自己快速的建立一个内存服务器了。拿这个例子来看,我们可能需要一个这样的对象

  1. class Todo {
  2. id: string;
  3. desc: string;
  4. completed: boolean;
  5. }

对应的JSON应该是这样的

  1. {
  2. "data": [
  3. {
  4. "id": "f823b191-7799-438d-8d78-fcb1e468fc78",
  5. "desc": "blablabla",
  6. "completed": false
  7. },
  8. {
  9. "id": "c316a3bf-b053-71f9-18a3-0073c7ee3b76",
  10. "desc": "tetssts",
  11. "completed": false
  12. },
  13. {
  14. "id": "dd65a7c0-e24f-6c66-862e-0999ea504ca0",
  15. "desc": "getting up",
  16. "completed": false
  17. }
  18. ]
  19. }

首先我们需要安装angular-in-memory-web-api,输入npm install --save angular-in-memory-web-api
然后在Todo文件夹下创建一个文件src\app\todo\todo-data.ts

  1. import { InMemoryDbService } from 'angular-in-memory-web-api';
  2. import { Todo } from './todo.model';
  3. export class InMemoryTodoDbService implements InMemoryDbService {
  4. createDb() {
  5. let todos: Todo[] = [
  6. {id: "f823b191-7799-438d-8d78-fcb1e468fc78", desc: 'Getting up', completed: true},
  7. {id: "c316a3bf-b053-71f9-18a3-0073c7ee3b76", desc: 'Go to school', completed: false}
  8. ];
  9. return {todos};
  10. }
  11. }

可以看到,我们创建了一个实现InMemoryDbService的内存数据库,这个数据库其实也就是把数组传入进去。接下来我们要更改src\app\app.module.ts,加入类引用和对应的模块声明:

  1. import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
  2. import { InMemoryTodoDbService } from './todo/todo-data';

然后在imports数组中紧挨着HttpModule加上InMemoryWebApiModule.forRoot(InMemoryTodoDbService),

现在我们在service中试着调用我们的“假web服务”吧

  1. import { Injectable } from '@angular/core';
  2. import { Http, Headers } from '@angular/http';
  3. import { UUID } from 'angular2-uuid';
  4. import 'rxjs/add/operator/toPromise';
  5. import { Todo } from './todo.model';
  6. @Injectable()
  7. export class TodoService {
  8. //定义你的假WebAPI地址,这个定义成什么都无所谓
  9. //只要确保是无法访问的地址就好
  10. private api_url = 'api/todos';
  11. private headers = new Headers({'Content-Type': 'application/json'});
  12. constructor(private http: Http) { }
  13. // POST /todos
  14. addTodo(desc:string): Promise<Todo> {
  15. let todo = {
  16. id: UUID.UUID(),
  17. desc: desc,
  18. completed: false
  19. };
  20. return this.http
  21. .post(this.api_url, JSON.stringify(todo), {headers: this.headers})
  22. .toPromise()
  23. .then(res => res.json().data as Todo)
  24. .catch(this.handleError);
  25. }
  26. private handleError(error: any): Promise<any> {
  27. console.error('An error occurred', error);
  28. return Promise.reject(error.message || error);
  29. }
  30. }

上面的代码我们看到定义了一个api_url = 'api/todos',你可能会问这个是怎么来的?其实这个我们改写成api_url = 'blablabla/nahnahnah'也无所谓,因为这个内存web服务的机理是拦截web访问,也就是说随便什么地址都可以,内存web服务会拦截这个地址并解析你的请求是否满足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的构造函数中我们注入了Http,而angular的Http封装了大部分我们需要的方法,比如例子中的增加一个todo,我们就调用this.http.post(url, body, options),上面代码中的.post(this.api_url, JSON.stringify(todo), {headers: this.headers})含义是:构造一个POST类型的HTTP请求,其访问的url是this.api_url,request的body是一个JSON(把todo对象转换成JSON),在参数配置中我们配置了request的header。

这个请求发出后返回的是一个Observable(可观察对象),我们把它转换成Promise然后处理res(Http Response)。Promise提供异步的处理,注意到then中的写法,这个和我们传统编程写法不大一样,叫做lamda表达式,相当于是一个匿名函数,(input parameters) => expression=>前面的是函数的参数,后面的是函数体。

还要一点需要强调的是:在用内存Web服务时,一定要注意res.json().data中的data属性必须要有,因为内存web服务坑爹的在返回的json中加了data对象,你真正要得到的json是在这个data里面。

下一步我们来更改Todo组件的addTodo方法以便可以使用我们新的异步http方法

  1. addTodo(){
  2. this.service
  3. .addTodo(this.desc)
  4. .then(todo => {
  5. this.todos = [...this.todos, todo];
  6. this.desc = '';
  7. });
  8. }

这里面的前半部分应该还是好理解的:this.service.addTodo(this.desc)是调用service的对应方法而已,但后半部分是什么鬼?...这个貌似省略号的东东是ES7中计划提供的Object Spread操作符,它的功能是将对象或数组“打散,拍平”。这么说可能还是不懂,举例子吧:

  1. let arr = [1,2,3];
  2. let arr2 = [...arr];
  3. arr2.push(4);
  4. // arr2 变成了 [1,2,3,4]
  5. // arr 保存原来的样子
  6. let arr3 = [0, 1, 2];
  7. let arr4 = [3, 4, 5];
  8. arr3.push(...arr4);
  9. // arr3变成了[0, 1, 2, 3, 4, 5]
  10. let arr5 = [0, 1, 2];
  11. let arr6 = [-1, ...arr5, 3];
  12. // arr6 变成了[-1, 0, 1, 2, 3]

所以呢我们上面的this.todos = [...this.todos, todo];相当于为todos增加一个新元素,和push很像,那为什么不用push呢?因为这样构造出来的对象是全新的,而不是引用的,在现代编程中一个明显的趋势是不要在过程中改变输入的参数。第二个原因是这样做会带给我们极大的便利性和编程的一致性。下面通过给我们的例子添加几个功能,我们来一起体会一下。
首先更改src\app\todo\todo.service.ts

  1. //src\app\todo\todo.service.ts
  2. import { Injectable } from '@angular/core';
  3. import { Http, Headers } from '@angular/http';
  4. import { UUID } from 'angular2-uuid';
  5. import 'rxjs/add/operator/toPromise';
  6. import { Todo } from './todo.model';
  7. @Injectable()
  8. export class TodoService {
  9. private api_url = 'api/todos';
  10. private headers = new Headers({'Content-Type': 'application/json'});
  11. constructor(private http: Http) { }
  12. // POST /todos
  13. addTodo(desc:string): Promise<Todo> {
  14. let todo = {
  15. id: UUID.UUID(),
  16. desc: desc,
  17. completed: false
  18. };
  19. return this.http
  20. .post(this.api_url, JSON.stringify(todo), {headers: this.headers})
  21. .toPromise()
  22. .then(res => res.json().data as Todo)
  23. .catch(this.handleError);
  24. }
  25. // PUT /todos/:id
  26. toggleTodo(todo: Todo): Promise<Todo> {
  27. const url = `${this.api_url}/${todo.id}`;
  28. console.log(url);
  29. let updatedTodo = Object.assign({}, todo, {completed: !todo.completed});
  30. return this.http
  31. .put(url, JSON.stringify(updatedTodo), {headers: this.headers})
  32. .toPromise()
  33. .then(() => updatedTodo)
  34. .catch(this.handleError);
  35. }
  36. // DELETE /todos/:id
  37. deleteTodoById(id: string): Promise<void> {
  38. const url = `${this.api_url}/${id}`;
  39. return this.http
  40. .delete(url, {headers: this.headers})
  41. .toPromise()
  42. .then(() => null)
  43. .catch(this.handleError);
  44. }
  45. // GET /todos
  46. getTodos(): Promise<Todo[]>{
  47. return this.http.get(this.api_url)
  48. .toPromise()
  49. .then(res => res.json().data as Todo[])
  50. .catch(this.handleError);
  51. }
  52. private handleError(error: any): Promise<any> {
  53. console.error('An error occurred', error);
  54. return Promise.reject(error.message || error);
  55. }
  56. }

然后更新src\app\todo\todo.component.ts

  1. import { Component, OnInit } from '@angular/core';
  2. import { TodoService } from './todo.service';
  3. import { Todo } from './todo.model';
  4. @Component({
  5. selector: 'app-todo',
  6. templateUrl: './todo.component.html',
  7. styleUrls: ['./todo.component.css'],
  8. providers: [TodoService]
  9. })
  10. export class TodoComponent implements OnInit {
  11. todos : Todo[] = [];
  12. desc: string = '';
  13. constructor(private service: TodoService) {}
  14. ngOnInit() {
  15. this.getTodos();
  16. }
  17. addTodo(){
  18. this.service
  19. .addTodo(this.desc)
  20. .then(todo => {
  21. this.todos = [...this.todos, todo];
  22. this.desc = '';
  23. });
  24. }
  25. toggleTodo(todo: Todo) {
  26. const i = this.todos.indexOf(todo);
  27. this.service
  28. .toggleTodo(todo)
  29. .then(t => {
  30. this.todos = [
  31. ...this.todos.slice(0,i),
  32. t,
  33. ...this.todos.slice(i+1)
  34. ];
  35. });
  36. }
  37. removeTodo(todo: Todo) {
  38. const i = this.todos.indexOf(todo);
  39. this.service
  40. .deleteTodoById(todo.id)
  41. .then(()=> {
  42. this.todos = [
  43. ...this.todos.slice(0,i),
  44. ...this.todos.slice(i+1)
  45. ];
  46. });
  47. }
  48. getTodos(): void {
  49. this.service
  50. .getTodos()
  51. .then(todos => this.todos = [...todos]);
  52. }
  53. }

更新模板文件src\app\todo\todo.component.html

  1. <section class="todoapp">
  2. <header class="header">
  3. <h1>Todos</h1>
  4. <input class="new-todo" placeholder="What needs to be done?" autofocus="" [(ngModel)]="desc" (keyup.enter)="addTodo()">
  5. </header>
  6. <section class="main" *ngIf="todos?.length > 0">
  7. <input class="toggle-all" type="checkbox">
  8. <ul class="todo-list">
  9. <li *ngFor="let todo of todos" [class.completed]="todo.completed">
  10. <div class="view">
  11. <input class="toggle" type="checkbox" (click)="toggleTodo(todo)" [checked]="todo.completed">
  12. <label (click)="toggleTodo(todo)">{{todo.desc}}</label>
  13. <button class="destroy" (click)="removeTodo(todo); $event.stopPropagation()"></button>
  14. </div>
  15. </li>
  16. </ul>
  17. </section>
  18. <footer class="footer" *ngIf="todos?.length > 0">
  19. <span class="todo-count">
  20. <strong>{{todos?.length}}</strong> {{todos?.length == 1 ? 'item' : 'items'}} left
  21. </span>
  22. <ul class="filters">
  23. <li><a href="">All</a></li>
  24. <li><a href="">Active</a></li>
  25. <li><a href="">Completed</a></li>
  26. </ul>
  27. <button class="clear-completed">Clear completed</button>
  28. </footer>
  29. </section

更新组件的css样式:src\app\todo\todo.component.css

  1. .todoapp {
  2. background: #fff;
  3. margin: 130px 0 40px 0;
  4. position: relative;
  5. box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
  6. 0 25px 50px 0 rgba(0, 0, 0, 0.1);
  7. }
  8. .todoapp input::-webkit-input-placeholder {
  9. font-style: italic;
  10. font-weight: 300;
  11. color: #e6e6e6;
  12. }
  13. .todoapp input::-moz-placeholder {
  14. font-style: italic;
  15. font-weight: 300;
  16. color: #e6e6e6;
  17. }
  18. .todoapp input::input-placeholder {
  19. font-style: italic;
  20. font-weight: 300;
  21. color: #e6e6e6;
  22. }
  23. .todoapp h1 {
  24. position: absolute;
  25. top: -155px;
  26. width: 100%;
  27. font-size: 100px;
  28. font-weight: 100;
  29. text-align: center;
  30. color: rgba(175, 47, 47, 0.15);
  31. -webkit-text-rendering: optimizeLegibility;
  32. -moz-text-rendering: optimizeLegibility;
  33. text-rendering: optimizeLegibility;
  34. }
  35. .new-todo,
  36. .edit {
  37. position: relative;
  38. margin: 0;
  39. width: 100%;
  40. font-size: 24px;
  41. font-family: inherit;
  42. font-weight: inherit;
  43. line-height: 1.4em;
  44. border: 0;
  45. color: inherit;
  46. padding: 6px;
  47. border: 1px solid #999;
  48. box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
  49. box-sizing: border-box;
  50. -webkit-font-smoothing: antialiased;
  51. -moz-osx-font-smoothing: grayscale;
  52. }
  53. .new-todo {
  54. padding: 16px 16px 16px 60px;
  55. border: none;
  56. background: rgba(0, 0, 0, 0.003);
  57. box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
  58. }
  59. .main {
  60. position: relative;
  61. z-index: 2;
  62. border-top: 1px solid #e6e6e6;
  63. }
  64. label[for='toggle-all'] {
  65. display: none;
  66. }
  67. .toggle-all {
  68. position: absolute;
  69. top: -55px;
  70. left: -12px;
  71. width: 60px;
  72. height: 34px;
  73. text-align: center;
  74. border: none; /* Mobile Safari */
  75. }
  76. .toggle-all:before {
  77. content: '❯';
  78. font-size: 22px;
  79. color: #e6e6e6;
  80. padding: 10px 27px 10px 27px;
  81. }
  82. .toggle-all:checked:before {
  83. color: #737373;
  84. }
  85. .todo-list {
  86. margin: 0;
  87. padding: 0;
  88. list-style: none;
  89. }
  90. .todo-list li {
  91. position: relative;
  92. font-size: 24px;
  93. border-bottom: 1px solid #ededed;
  94. }
  95. .todo-list li:last-child {
  96. border-bottom: none;
  97. }
  98. .todo-list li.editing {
  99. border-bottom: none;
  100. padding: 0;
  101. }
  102. .todo-list li.editing .edit {
  103. display: block;
  104. width: 506px;
  105. padding: 12px 16px;
  106. margin: 0 0 0 43px;
  107. }
  108. .todo-list li.editing .view {
  109. display: none;
  110. }
  111. .todo-list li .toggle {
  112. text-align: center;
  113. width: 40px;
  114. /* auto, since non-WebKit browsers doesn't support input styling */
  115. height: auto;
  116. position: absolute;
  117. top: 0;
  118. bottom: 0;
  119. margin: auto 0;
  120. border: none; /* Mobile Safari */
  121. -webkit-appearance: none;
  122. appearance: none;
  123. }
  124. .todo-list li .toggle:after {
  125. 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>');
  126. }
  127. .todo-list li .toggle:checked:after {
  128. 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>');
  129. }
  130. .todo-list li label {
  131. word-break: break-all;
  132. padding: 15px 60px 15px 15px;
  133. margin-left: 45px;
  134. display: block;
  135. line-height: 1.2;
  136. transition: color 0.4s;
  137. }
  138. .todo-list li.completed label {
  139. color: #d9d9d9;
  140. text-decoration: line-through;
  141. }
  142. .todo-list li .destroy {
  143. display: none;
  144. position: absolute;
  145. top: 0;
  146. right: 10px;
  147. bottom: 0;
  148. width: 40px;
  149. height: 40px;
  150. margin: auto 0;
  151. font-size: 30px;
  152. color: #cc9a9a;
  153. margin-bottom: 11px;
  154. transition: color 0.2s ease-out;
  155. }
  156. .todo-list li .destroy:hover {
  157. color: #af5b5e;
  158. }
  159. .todo-list li .destroy:after {
  160. content: '×';
  161. }
  162. .todo-list li:hover .destroy {
  163. display: block;
  164. }
  165. .todo-list li .edit {
  166. display: none;
  167. }
  168. .todo-list li.editing:last-child {
  169. margin-bottom: -1px;
  170. }
  171. .footer {
  172. color: #777;
  173. padding: 10px 15px;
  174. height: 20px;
  175. text-align: center;
  176. border-top: 1px solid #e6e6e6;
  177. }
  178. .footer:before {
  179. content: '';
  180. position: absolute;
  181. right: 0;
  182. bottom: 0;
  183. left: 0;
  184. height: 50px;
  185. overflow: hidden;
  186. box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
  187. 0 8px 0 -3px #f6f6f6,
  188. 0 9px 1px -3px rgba(0, 0, 0, 0.2),
  189. 0 16px 0 -6px #f6f6f6,
  190. 0 17px 2px -6px rgba(0, 0, 0, 0.2);
  191. }
  192. .todo-count {
  193. float: left;
  194. text-align: left;
  195. }
  196. .todo-count strong {
  197. font-weight: 300;
  198. }
  199. .filters {
  200. margin: 0;
  201. padding: 0;
  202. list-style: none;
  203. position: absolute;
  204. right: 0;
  205. left: 0;
  206. }
  207. .filters li {
  208. display: inline;
  209. }
  210. .filters li a {
  211. color: inherit;
  212. margin: 3px;
  213. padding: 3px 7px;
  214. text-decoration: none;
  215. border: 1px solid transparent;
  216. border-radius: 3px;
  217. }
  218. .filters li a:hover {
  219. border-color: rgba(175, 47, 47, 0.1);
  220. }
  221. .filters li a.selected {
  222. border-color: rgba(175, 47, 47, 0.2);
  223. }
  224. .clear-completed,
  225. html .clear-completed:active {
  226. float: right;
  227. position: relative;
  228. line-height: 20px;
  229. text-decoration: none;
  230. cursor: pointer;
  231. }
  232. .clear-completed:hover {
  233. text-decoration: underline;
  234. }
  235. /*
  236. Hack to remove background from Mobile Safari.
  237. Can't use it globally since it destroys checkboxes in Firefox
  238. */
  239. @media screen and (-webkit-min-device-pixel-ratio:0) {
  240. .toggle-all,
  241. .todo-list li .toggle {
  242. background: none;
  243. }
  244. .todo-list li .toggle {
  245. height: 40px;
  246. }
  247. .toggle-all {
  248. -webkit-transform: rotate(90deg);
  249. transform: rotate(90deg);
  250. -webkit-appearance: none;
  251. appearance: none;
  252. }
  253. }
  254. @media (max-width: 430px) {
  255. .footer {
  256. height: 50px;
  257. }
  258. .filters {
  259. bottom: 10px;
  260. }
  261. }

更新src\styles.css为如下

  1. /* You can add global styles to this file, and also import other style files */
  2. html, body {
  3. margin: 0;
  4. padding: 0;
  5. }
  6. button {
  7. margin: 0;
  8. padding: 0;
  9. border: 0;
  10. background: none;
  11. font-size: 100%;
  12. vertical-align: baseline;
  13. font-family: inherit;
  14. font-weight: inherit;
  15. color: inherit;
  16. -webkit-appearance: none;
  17. appearance: none;
  18. -webkit-font-smoothing: antialiased;
  19. -moz-osx-font-smoothing: grayscale;
  20. }
  21. body {
  22. font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
  23. line-height: 1.4em;
  24. background: #f5f5f5;
  25. color: #4d4d4d;
  26. min-width: 230px;
  27. max-width: 550px;
  28. margin: 0 auto;
  29. -webkit-font-smoothing: antialiased;
  30. -moz-osx-font-smoothing: grayscale;
  31. font-weight: 300;
  32. }
  33. :focus {
  34. outline: 0;
  35. }
  36. .hidden {
  37. display: none;
  38. }
  39. .info {
  40. margin: 65px auto 0;
  41. color: #bfbfbf;
  42. font-size: 10px;
  43. text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
  44. text-align: center;
  45. }
  46. .info p {
  47. line-height: 1;
  48. }
  49. .info a {
  50. color: inherit;
  51. text-decoration: none;
  52. font-weight: 400;
  53. }
  54. .info a:hover {
  55. text-decoration: underline;
  56. }

现在我们看看成果吧,现在好看多了

本节代码:https://github.com/wpcfan/awesome-tutorials/tree/chap03/angular2/ng2-tut

第一节:Angular 2.0 从0到1 (一)
第二节:Angular 2.0 从0到1 (二)
第三节:Angular 2.0 从0到1 (三)
第四节:Angular 2.0 从0到1 (四)
第五节:Angular 2.0 从0到1 (五)
第六节:Angular 2.0 从0到1 (六)
第七节:Angular 2.0 从0到1 (七)
第八节:Angular 2.0 从0到1 (八)
番外:Angular 2.0 从0到1 (八)
番外:Angular 2.0 从0到1 Rx—Redux你的Angular 2应用

Angular 2 从0到1 (三)的更多相关文章

  1. 黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (高级)

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (高级) 企业库验证应用程序模块之配置文件模式: ...

  2. 黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (初级)

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (初级) 企业库提供了一个很强大的验证应用程序模 ...

  3. SpringBoot从0到0.7——第三天

    SpringBoot从0到0.7--第三天 今天学习整合JDBC,连接数据库的增删改查,写出来容易,理解原理读懂代码才是主要的. 首先创建项目,勾选上一下模块 在application.yml添加 s ...

  4. 1、Cocos2dx 3.0游戏开发三找一小块前言

    尊重开发人员的劳动成果,转载的时候请务必注明出处:http://blog.csdn.net/haomengzhu/article/details/27094663 前言 Cocos2d-x 是一个通用 ...

  5. angular --- s3core移动端项目(三)

    angular.module('myApp') .directive('listActive',functon(){ return { restrict:'A', scope:{ listActive ...

  6. C#6.0语言规范(三) 基本概念

    应用程序启动 具有入口点的程序集称为应用程序.运行应用程序时,会创建一个新的应用程序域.应用程序的几个不同实例可以同时存在于同一台机器上,并且每个实例都有自己的应用程序域. 应用程序域通过充当应用程序 ...

  7. Angular动态表单生成(三)

    ng-dynamic-forms实践篇(上) 定个小目标 先来定个小目标吧,我们要实现的效果: 动态生成一个表单,里面的字段如下: 字段名称 字段类型 验证 备注 姓名 text 必填,长度小于15 ...

  8. 零基础快速入门SpringBoot2.0教程 (三)

    一.SpringBoot Starter讲解 简介:介绍什么是SpringBoot Starter和主要作用 1.官网地址:https://docs.spring.io/spring-boot/doc ...

  9. Vijos1144 皇宫看守 (0/1/2三种状态的普通树形Dp)

    题意: 给出一个树以及一些覆盖每个点的花费,求每个点都能被自己被覆盖,或者相邻的点被覆盖的最小价值. 细节: 其实我乍一眼看过去还以为是 战略游戏 的复制版 可爱的战略游戏在这里QAQ(请原谅这波广告 ...

随机推荐

  1. HDU 4882 ZCC Loves Codefires (贪心)

    ZCC Loves Codefires 题目链接: http://acm.hust.edu.cn/vjudge/contest/121349#problem/B Description Though ...

  2. iOS学习之自动布局

    Autolayout: 最重要的两个概念: 约束:对控件位置和大小的限定条件 参照:对控件设置的约束是相对于哪一个视图而言的 自动布局的核心计算公式: obj1.property1 =(obj2.pr ...

  3. sping配置文件中引入properties文件方式

    <!-- 用于引入 jdbc有配置文件参数 可以使用PropertyPlaceholderConfigurer 或者PropertyOverrideConfigurer --> <b ...

  4. thymeleaf中的th:with用法

    局部变量,th:with能定义局部变量: <div th:with="firstPer=${persons[0]}"> <p> The name of th ...

  5. 最长不下降子序列nlogn算法详解

    今天花了很长时间终于弄懂了这个算法……毕竟找一个好的讲解真的太难了,所以励志我要自己写一个好的讲解QAQ 这篇文章是在懂了这个问题n^2解决方案的基础上学习. 解决的问题:给定一个序列,求最长不下降子 ...

  6. SRV记录说明

      SRV记录是DNS服务器的数据库中支持的一种资源记录的类型,它记录了哪台计算机提供了哪个服务这么一个简单的信息 SRV 记录:一般是为Microsoft的活动目录设置时的应用.DNS可以独立于活动 ...

  7. Java中throws和throw的区别讲解

    当然,你需要明白异常在Java中式以一个对象来看待.并且所有系统定义的编译和运行异常都可以由系统自动抛出,称为标准异常,但是一般情况下Java 强烈地要求应用程序进行完整的异常处理,给用户友好的提示, ...

  8. Codeforces Gym 100733H Designation in the Mafia flyod

    Designation in the MafiaTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/c ...

  9. Oracle 生成随机密码

    需求:需要定期更改密码.要求是1.密码位数11位.2.必须包含大小写字母.数字.特殊字符.3.排除一些特殊字符如().@.& oracle数据库中有可已生成随机密码包dbms_random,但 ...

  10. 【ZZ】大数据架构师基础:hadoop家族,Cloudera系列产品介绍

    http://www.36dsj.com/archives/17192 大数据我们都知道hadoop,可是还会各种各样的技术进入我们的视野:Spark,Storm,impala,让我们都反映不过来.为 ...