[](()第二例:ToDoList
功能概述: 在第一例的基础上, 我们还可以通过点击checkBox来实时更改数据状态
HTML:
搜索条
<input type=“text” [(ngModel)]=“keyword” (keyup)=“doAdd($event)” />
正在运行
<input type=“checkbox” [(ngModel)]=“item.status” (change)="changeCheckBox() "/>{{ item.title }}
<button (click)=“onDelete(i)”>×
成功执行
<input type=“checkbox” [(ngModel)]=“item.status” (change)=“changeCheckBox()” />{{ item.title }}
<button (click)=“onDelete(i)”>×
CSS:
h2{
text-align: center;
}
.toDoList{
margin: 20px auto;
width: 400px;
li{
line-height: 60px;
}
}
TS:
import { Component, OnInit } from ‘@angular/core’;
import { StorageService } from ‘…/…/services/storage.service’;
@Component({
selector: ‘app-to-do-list’,
templateUrl: ‘./to-do-list.c 《大厂前端面试题解析+Web核心总结学习笔记+企业项目实战源码+最新高清讲解视频》无偿开源 徽信搜索公众号【编程进阶路】 omponent.html’,
styleUrls: [‘./to-do-list.component.scss’],
})
export class ToDoListComponent implements OnInit {
public toDoData = [];
public keyword = ‘’;
public status = false;
constructor(public storageService: StorageService) {}
ngOnInit(): void {
const storageToDoList = this.storageService.get(‘toDoList’);
if (storageToDoList) {
this.toDoData = storageToDoList;
}
}
public doAdd(e: any): void {
if (e.keyCode === 13) {
if (this.toDoDataHasKeyWord(this.toDoData, this.keyword)) {
this.toDoData.push({ title: this.keyword, status: this.status });
this.keyword = ‘’;
this.storageService.set(‘toDoList’, this.toDoData);
}
}
}
public onDelete(key: number): void {
this.toDoData.splice(key, 1);
this.storageService.set(‘toDoList’, this.toDoData);
}
public toDoDataHasKeyWord(toDoData: any[], keyword: any): boolean {
// 异步问题先不用
// this.toDoData.forEach((item) => {
// });
return !toDoData.some((item) => item.title === keyword);
// const { length } = toDoData;
// for (let i = 0; i < length; ++i) {
// if (toDoData[i].title === keyword) {
// return false;
// }
// }
// return true;
// }
}
public changeCheckBox(): void {
this.storageService.set(‘toDoList’, this.toDoData);
}
}
结果截图:
[](()他们的服务和数据持久化
Service:
import { Injectable } from ‘@angular/core’;
@Injectable({
providedIn: ‘root’,
})
export class StorageService {
constructor() {}
public set(key: string, value: any): void {
localStorage.setItem(key, JSON.stringify(value));
}
public get(key: string): any {
return JSON.parse(localStorage.getItem(key));
}
public remove(key: string): void {
localStorage.removeItem(key);
}
}