待办事项案例
- 绘制html页面
```html
todolist
<h2>待办事项</h2>
<ul>
<li *ngFor="let item of todoList; let key=index;" [hidden]='item.status==1'>
<input type="checkbox" name="todolist" id="todolist" [(ngModel)]='item.status'>
{{ item.title }} -------------------
<button (click)='deleteData(key)'>X</button>
</li>
</ul>
<h2>已完成事项</h2>
<ul>
<li *ngFor="let item of todoList; let key=index;" [hidden]='item.status==0'>
<input type="checkbox" name="todolist" id="todolist" [(ngModel)]='item.status'>
{{ item.title }} -------------------
<button (click)='deleteData(key)'>X</button>
</li>
</ul>
2.
绘制less样式
```less
h2 {
text-align: center;
}
.todolist {
width: 400px;
margin: 20px auto;
.form-input {
margin-bottom: 20px;
width: 300px;
height: 32px;
}
}
- 编写typescript ```typescript import { Component, OnInit } from ‘@angular/core’; import { element } from ‘protractor’;
@Component({ selector: ‘app-todolist’, templateUrl: ‘./todolist.component.html’, styleUrls: [‘./todolist.component.css’] }) export class TodolistComponent implements OnInit {
public keyword:string; public todoList:any[] = [];
constructor() { }
ngOnInit(): void { }
doAdd(e){ // 监控按下的键是否为回车键 if(e.keyCode != 13) { return; } if(this.todoList.indexOf(this.keyword) < 0) { if(this.todolistHaskeyword(this.todoList, this.keyword)) { alert(‘该待办事项已录入’); return; } // 将keyword添加到todoList中 this.todoList.push({ title: this.keyword, status: 0 // 0.待办事项;1.已完成事项 }); } this.keyword = ‘’; }
deleteData(key) { // 从todoList中移除key位置的1个元素 this.todoList.splice(key, 1); }
// 判断对象数组中是否存在某个元素
todolistHaskeyword(todolist:any[], keyword:any) { let result = false; todolist.forEach(element => { if(element.title == keyword) { // forEach的值不能return到外面,所以此处不能直接写: return true; result = true; } }); return result; } } ```