搜索组件HTML:
<h2>搜索历史</h2>
<div class="search">
<input type="text" [(ngModel)]="keyword" />
<button (click)="doSearch()">搜索</button>
<hr />
<ul>
<li *ngFor="let item of historyList; let key = index">
{{ item }} ------ <button (click)="deleteHistroy(key)">X</button>
</li>
</ul>
</div>
搜索组件TS:
import { Component, OnInit } from '@angular/core';
import { StorageService } from '../../services/storage.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss'],
})
export class SearchComponent implements OnInit {
public keyword: string = ''; // 搜索词
public historyList: any[] = []; // 搜索历史
constructor(public storage: StorageService) {}
ngOnInit(): void {
console.log('页面刷新会触发这个生命周期函数');
// 页面刷新或重启后,从localStorage中拿数据
let historyList = this.storage.get('historyList');
if (historyList) {
// 若不为空,则更新数据
this.historyList = historyList;
}
}
doSearch() {
if (this.historyList.indexOf(this.keyword) == -1) {
// 数组中,没有就新增
this.historyList.push(this.keyword); // 插入数组
this.storage.set('searchlist', this.historyList);
}
this.keyword = '';
}
deleteHistroy(key: any) {
this.historyList.splice(key, 1); // 从key的位置开始,删除之后的1个元素(包括第key个)
this.storage.set('searchlist', this.historyList);
}
}
todolist组件html
<h2>todoList</h2>
<div class="todolist">
<input
class="form_input"
type="text"
[(ngModel)]="keyword"
(keyup)="doAdd($event)"
/>
<hr />
<h3>待办事项</h3>
<ul>
<li
*ngFor="let item of todolist; let key = index"
[hidden]="item.status == 1"
>
<!--
数据status为0表示代办,0==1为false,使这里不隐藏,[ ] 代表数据从模型流向视图
通过复选框的双向数据绑定,修改status,从而影响视图这边的显示隐藏
-->
<input
type="checkbox"
[(ngModel)]="item.status"
(change)="checkboxChage()"
/>
{{ item.title }} ------ <button (click)="deleteData(key)">X</button>
</li>
</ul>
<h3>已完成事项</h3>
<ul>
<li
*ngFor="let item of todolist; let key = index"
[hidden]="item.status == 0"
>
<!-- 数据status为1表示已办,1==0为false,使这里不隐藏 -->
<input
type="checkbox"
[(ngModel)]="item.status"
(change)="checkboxChage()"
/>
{{ item.title }} ------ <button (click)="deleteData(key)">X</button>
</li>
</ul>
</div>
todolist组件ts
import { Component, OnInit } from '@angular/core';
import { StorageService } from '../../services/storage.service';
/* 服务不能调用组件,服务可以调用服务 */
@Component({
selector: 'app-todolist',
templateUrl: './todolist.component.html',
styleUrls: ['./todolist.component.scss'],
})
export class TodolistComponent implements OnInit {
// 服务实例化
// var storage=new StorageService(); 不推荐写法
// 推荐构造函数写法
constructor(public storage: StorageService) {}
ngOnInit(): void {
console.log('页面刷新会触发这个生命周期函数');
// 页面刷新或重启后,从localStorage中拿数据
let todolist = this.storage.get('todolist');
if (todolist) {
// 若不为空,则更新数据
this.todolist = todolist;
}
}
public keyword: string = '';
public todolist: any[] = [];
doAdd(e: any) {
// 按下回车后插入数组
if (e.keyCode == 13) {
if (!this.todolistHasKeyword(this.todolist, this.keyword)) {
// 数组中不存在一样的事务,则插入
this.todolist.push({
title: this.keyword,
status: 0, // 默认是0,表示代办!
});
this.storage.set('todolist', this.todolist); // 更新localstorage
} else {
alert('数据已经存在');
}
this.keyword = ''; // 清空输入框
}
}
deleteData(key: any) {
this.todolist.splice(key, 1); // 删除此项
this.storage.set('todolist', this.todolist); // 更新localstorage
}
checkboxChage() {
console.log('事件触发了');
this.storage.set('todolist', this.todolist); // 更新localstorage
}
todolistHasKeyword(todolist: any, keyword: any) {
// 判断数组中是否有相同的项,若有返回true
if (!keyword) return false;
for (var i = 0; i < todolist.length; i++) {
if (todolist[i].title == keyword) {
return true;
}
}
return false;
}
}
公共方法放在服务中,组件要用,引入即可。用指令创建后,根模块和组件中均要引入声明配置!
(这里将操作localStorage的方法写在服务中)
storage.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class StorageService {
constructor() {}
public set(key: string, value: any) {
localStorage.setItem(key, JSON.stringify(value)); // 将JSON对象转为字符串,存入localstorage
}
get(key: string) {
return JSON.parse(String(localStorage.getItem(key)));
}
remove(key: string) {
localStorage.removeItem(key);
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { StorageService } from './services/storage.service';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SearchComponent } from './components/search/search.component';
import { TodolistComponent } from './components/todolist/todolist.component';
@NgModule({
declarations: [AppComponent, SearchComponent, TodolistComponent],
imports: [BrowserModule, AppRoutingModule, FormsModule],
providers: [StorageService],
bootstrap: [AppComponent],
})
export class AppModule {}
app.module.html
<app-search></app-search>
<br /><br />
<app-todolist></app-todolist>
项目结构
引入模块和声明配置,分别是自己写的公共服务和双向绑定