待办事项案例

  1. 绘制html页面 ```html

    todolist


  1. <h2>待办事项</h2>
  2. <ul>
  3. <li *ngFor="let item of todoList; let key=index;" [hidden]='item.status==1'>
  4. <input type="checkbox" name="todolist" id="todolist" [(ngModel)]='item.status'>
  5. {{ item.title }} -------------------
  6. <button (click)='deleteData(key)'>X</button>
  7. </li>
  8. </ul>
  9. <h2>已完成事项</h2>
  10. <ul>
  11. <li *ngFor="let item of todoList; let key=index;" [hidden]='item.status==0'>
  12. <input type="checkbox" name="todolist" id="todolist" [(ngModel)]='item.status'>
  13. {{ item.title }} -------------------
  14. <button (click)='deleteData(key)'>X</button>
  15. </li>
  16. </ul>

  1. 2.
  2. 绘制less样式
  3. ```less
  4. h2 {
  5. text-align: center;
  6. }
  7. .todolist {
  8. width: 400px;
  9. margin: 20px auto;
  10. .form-input {
  11. margin-bottom: 20px;
  12. width: 300px;
  13. height: 32px;
  14. }
  15. }
  1. 编写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); }

  1. // 判断对象数组中是否存在某个元素

todolistHaskeyword(todolist:any[], keyword:any) { let result = false; todolist.forEach(element => { if(element.title == keyword) { // forEach的值不能return到外面,所以此处不能直接写: return true; result = true; } }); return result; } } ```