一、history搜索框
1-1.history.component.html
<input type="text" (keyup)="handleInput($event)" [(ngModel)]="msg"><ul> <li *ngFor="let item of lists;let key=index" (click)="handleClick(key)">{{item}}</li></ul>
1-2.history.component.ts
import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-history', templateUrl: './history.component.html', styleUrls: ['./history.component.css']})export class HistoryComponent implements OnInit { msg = ""; lists: string[] = []; constructor() { } ngOnInit(): void { if (localStorage.getItem("lists")) { let lists = JSON.parse(<string>localStorage.getItem('lists')); this.lists = lists } } handleInput(e: any) { if (e.keyCode == 13) { this.lists.push(this.msg); this.msg = ""; localStorage.setItem("lists", JSON.stringify(this.lists)); } } handleClick(key: number) { this.lists.splice(key, 1); localStorage.setItem("lists", JSON.stringify(this.lists)); }}
二、todoList
2-1.todo-list.component.html
<input type="text" [(ngModel)]="msg" (keyup)="handleInput($event)"><p>未完成 {{todo.length}}</p><div *ngFor="let item of todo;let key=index"> <input type="checkbox" [checked]="item.checked" (click)="handleClick(item,key)"> {{item.value}}</div><p>已完成 {{complete.length}}</p><div *ngFor="let item of complete;let key=index"> <input type="checkbox" [checked]="item.checked" (click)="handleClick(item,key)"> {{item.value}}</div>
2-2.todo-list.component.ts
import { Component, OnInit } from '@angular/core';type data = { value: string, checked: Boolean };@Component({ selector: 'app-todo-list', templateUrl: './todo-list.component.html', styleUrls: ['./todo-list.component.css']})export class TodoListComponent implements OnInit { msg = ""; todo: data[] = []; complete: data[] = []; constructor() { } ngOnInit(): void { if (localStorage.getItem("todo")) { this.todo = JSON.parse(<string>localStorage.getItem("todo")) }; if (localStorage.getItem("complete")) { this.complete = JSON.parse(<string>localStorage.getItem("complete")) } } handleInput(e: any) { if (e.keyCode == 13) { this.todo.unshift({ value: this.msg, checked: false, }); this.msg = ""; localStorage.setItem("todo", JSON.stringify(this.todo)) } } handleClick(item: data, key: number) { item.checked = !item.checked if (item.checked) { this.todo.splice(key, 1); this.complete.unshift(item) } else { this.complete.splice(key, 1); this.todo.unshift(item); } localStorage.setItem("todo", JSON.stringify(this.todo)); localStorage.setItem("complete", JSON.stringify(this.complete)); }}
三、Tips报错解决
1、ngModel双向数据绑定需要在app.module.ts中导入FormsModule模块2、不能直接定义todo:object=[];这样每个item中的属性也会为object,渲染For循环item.value时会报错。使用自定义类型 type data = { value: string, checked: Boolean };定义对象中的每个属性类型3、使用JSON.parse(localStorage.getItem())时不能直接将string|null类型的数据赋值给stringif判断localStorage存在后直接断言string类型 JSON.parse(<string>localStorage.getItem("complete"))