Angular2初学笔记之 做一个todolist

因为之前简单学习过vue,它和angular2的概念很多都是一样的,所以学angular2也觉得容易上手。
首先安装angular-cli

cnpm install -g angular-cli

安装完成后开始创建自己的项目

ng new todolist
cd todolist
cnpm install
ng serve

项目架构就搭建好了,可以到 http://localhost:4200/ 查看。
接下来我们来修改todolist/src/app目录下的AppComponent这个组件。
首先打开app.component.html,页面初步结构如下:

<h1>
  {{title}}
</h1>
<input type="text" [(ngModel)]="newItem" (keyup.enter)="addNew()">
<ul>
    <li *ngFor="let item of items" [class.isFinished]="item.isFinished" (click)="toggleFinish(item)">{{item.label}}</li>
</ul>

h1标签直接绑定了title;
input标签双向绑定了newItem,并在按下回车键后执行addNew(),将newItem添加到items中;
li标签使用*ngFor 遍历items,显示出item.label属性,并通过item.isFinished是否为true选择性的添加样式;

结构确定好之后,开始修改app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my todolist';
  items = [{label:'apple',isFinished:false},{label:'orange',isFinished:false}];
  newItem = '';
  addNew = function(){
    this.items.push({label:this.newItem, isFinished:false});
    this.newItem = '';
  };
  toggleFinish = function (item) {
    item.isFinished = ! item.isFinished;
  }
}

给items赋一个初始值,定义addNew和toggleFinish这两个函数。
这样就完成了简单的一个todolist。
这里写图片描述
实际在使用上和vue没有太大差别。
vue的一个组件的template script style全部都在一个文件中,而angular2则细分为多个文件放在一个文件夹中。

猜你喜欢

转载自blog.csdn.net/shengandshu/article/details/60372389