一、原理
1、搜索框输入文本,点击搜索,数据添加到数组
2、数组绑定到搜索历史的 页面 <li>标签
3、标签后跟按钮可删除
# ts 文件定义
# 搜索内容
public keyWord: string;
# 缓存搜索历史
public historyList: any[] = [];
# 搜索历史加入数组
doSearch() {
if (this.historyList.indexOf(this.keyWord) < 0) {
this.historyList.push(this.keyWord);
}
this.keyWord = '';
}
# 删除搜索历史
deleteHistory(key) {
this.historyList.splice(key, 1);
}
# html 文件绑定使用
<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)="deleteHistory(key)">x</button>
</li>
</ul>
</div>
二、ToDoList
# ts 文件定义
public keyWord: any;
public historyList: any[] = [];
doAdd(e) {
if (e.keyCode == 13) {
if (!this.todolistHasKeyword(this.historyList, this.keyWord)) {
this.historyList.push({
title: this.keyWord,
status: 0
});
} else {
alert('数据已经存在');
}
this.keyWord = '';
}
}
deleteHistory(key) {
this.historyList.splice(key, 1);
}
# 去重
todolistHasKeyword(todoList: any, keyword: any) {
// 异步会存在问题
// todoList.forEach( value => {
// if (value.title == keyword){
// return true;
// }
// });
if (keyword == '') { return true; }
for (let i = 0; i < todoList.length; i++) {
if (todoList[i].title == keyword){
return true;
}
}
return false;
}
# html 引用
<div class="todolist">
<input type="text" [(ngModel)]="keyWord" (keyup)="doAdd($event)"/>
<hr/>
<h3>待办事项</h3>
<ul>
<li *ngFor="let item of historyList; let key=index;" [hidden]="item.status==0">
<input type="checkbox" [(ngModel)]="item.status">
{{item.title}}-----<button (click)="deleteHistory(key)">x</button>
</li>
</ul>
<h3>以完成事项</h3>
<ul>
<li *ngFor="let item of historyList; let key=index;" [hidden]="item.status==1">
<input type="checkbox" [(ngModel)]="item.status">
{{item.title}}-----<button (click)="deleteHistory(key)">x</button>
</li>
</ul>
</div>