《todoList.component.html》:
<input type="text" [(ngModule)] = "userName" (keyup) ="addDate($event)">
// <button (click) = "addData()" >增加</button>
<hr>
<h2>正在进行</h2>
<ul>
<li *ngFor = "let item of list,let i= index" [hidden]= "item.status == 1">
< button (click) = "changeData(i,2)" > 改变状态</button>
{{item.userName}} //{{item}}
<button (click) = "deletData(i)"> 删除</button>
</li>
</ul>
<h2>已经完成</h2>
<ul>
<li *ngFor = "let item of list,let i= index" [hidden]= "item.status == 1">
<button (click) = "changeData(i,1)" > 改变状态</button>
{{item.userName}} //{{item}}
<button (click) = "deletData(i)"> 删除</button>
</li>
</ul>
《todoList.component.ts》:
export class todoListComponent implements OnInit {
public userName: any = "";
public list = [];
constructor(private storage:StorageService) {
}
ngOnInit() {
}
addData(e) {
if(e.keyCode == 13){
//每次增加的一个对象数据
var obj = {
userName:this.userName;
status:1
}
this.list.push (obj); // this.list.push (this.userName);
this.userName == "";
}
}
deleteData(key){
this.list.splice(key,1);
}
changeData(key,status) {
this.list[ key ].status = status ;
}
}
版本2: --- 增加缓存服务
《todoList.component.ts》:
import { StorageService } from '../../services/storage.service';
... ...
export classtodoListComponent implements OnInit {
public userName: any = "";
public list = [];
constructor(private storage:StorageService) {
}
ngOnInit() { //页面初始化获取缓存数据
var storageData = this.storage.getItem('todoList');
if( storageData){
this.list = storageData
}
}
addData(e) {
//1:从storage获取 todoList 的数据
//2:如果有数据,将新数据与这个数据拼接,重新写入
//3:如果没有数据,直接给storage写入
if(e.keyCode == 13){
var obj = {
username:this.username,
status:1
}
var todoList = this.storage.getItem('todoList);
if(todoList){
todoList.push(obj);
this.storage.setItem('todoList');
}else{
var arr = [];
arr.push(obj);
this.storage.setItem('todoList',arr);
}
this.list.push (obj); // this.list.push (this.userName);
this.userName == "";
}
}
deleteData(key){
this.list.splice(key,1);
}
changeData(key,status) {
this.list[ key ].status = status ;
this.storage.setItem('todoList',this.list);
}
};
《storage.service.ts》:
import { Injectable } from '@angular/core';
@Injectable() export class StorageService {
constructor() { }
setItem(key,value){
localStrage.setItem(key,JSON.stringify(value))
}
getItem(key){
return JSON.parse(localStrage.getItem(key));
}
removeItem(key){
localStorage.removeItem(key);
}