35Angular实现一个todoList
1 <div class="todolist"> 2 <h3>ToDoList</h3> 3 <input class="todo" type="text" [(ngModel)]="keyword" (keyup)=keyup($event)> 4 <p>代办事项:</p> 5 <h4 *ngFor="let item of todoList;let key = index;" [hidden]="item.state==1"> <!--选中了item.state等于1,那么这个item放到已完成事项中--> 6 <p> {{item.title}}-------<span (click)="delete(key)">X</span> <input type="checkbox" [(ngModel)]="item.state"> </p> 7 </h4> 8 9 <p>已完成事项:</p> 10 <h4 *ngFor="let item of todoList;let key=index;" [hidden]="item.state==0"> 11 <p>{{item.title}}-------<span (click)="delete(key)">X</span></p> 12 </h4> 13 </div>
1 import { Component, OnInit } from '@angular/core'; 2 3 @Component({ 4 selector: 'app-todolist', 5 templateUrl: './todolist.component.html', 6 styleUrls: ['./todolist.component.css'] 7 }) 8 export class TodolistComponent implements OnInit { 9 keyword:string='';//输入框中输入的关键词 10 state:any='';//状态,用来判断是待完成事项还是已完成事项 11 todoList:Array<any>=[];//包含关键词的数组,数组中每一个元素是一个对象(title:'',state:''); 12 13 constructor() { } 14 15 ngOnInit() { 16 } 17 18 keyup(e){ //鼠标弹起 19 if(e.keyCode==13){ //按下回车键 20 console.log(this.keyword); 21 if(this.hasKeyWord(this.keyword,this.todoList)){ //可以push到数组的条件是hasKeyWord()返回true,也就是keyword没有出现过 22 this.todoList.push({ 23 title: this.keyword, 24 state: 0, 25 }); 26 } 27 this.keyword='';//打印出keyword,要清空输入框 28 } 29 30 } 31 32 delete(keyIndex){ 33 console.log(keyIndex); 34 this.todoList.splice(keyIndex,1); 35 } 36 37 38 hasKeyWord(keyword:any,todoList:any){ //判断关键词是否在todoList中出现过的方法 39 for(let i=0;i<todoList.length;i++){ //循环遍历todoList数组 40 if(todoList[i].title==keyword){ //如果数组里有了keyword,返回false 41 return false; 42 } 43 } 44 return true;//返回true,说明没有keyword 45 } 46 47 48 49 }