列出搜索过的数据(类似京东顶部搜索框)
tip: 只要进行数据绑定,一定要先检查是否在app_module.ts中进行过formsModule的数据引入,如果没有进行引入,在数据绑定的时候会出现报错
例一:京东搜索,历史记录
html:
<div>
<input type="text" [(ngModel)]="keyword">
<button (click)="dosearch()">搜索</button>
<ul>
<li *ngFor="let item of historyList ; let key= index">{{item}}
<button (click)="deletehistory()">x</button>
</li>
</ul>
</div>
ts中:
public keyword:string="";
public historyList:any[]=[];
dosearch(){
console.log(this.keyword);
console.log(this.historyList.indexOf(this.keyword));
if(this.historyList.indexOf(this.keyword)==-1){
if(this.keyword !=""){
this.historyList.push(this.keyword);
this.keyword="";
}else{
console.log("请输入您要搜索的物品");
}
}else{
console.log("您搜索过此物品");
}
}
deletehistory(key){
this.historyList.splice(key,1);
}
解析:
console.log(this.keyword);获取输入框中的值。
this.historyList.indexOf(this.keyword)==-1 历史列表中的值是否等于-1
if(this.historyList.indexOf(this.keyword)==-1){ 判断历史列表中的值是否为-1
如果是-1则,
if(this.keyword !=""){
· 在判断输入框中的值是否为空,不为空,将输入框中的值赋值给历史列表
this.historyList.push(this.keyword);
this.keyword="";
如果为空,则进行提示
console.log("请输入您要搜索的物品");
如果不为-1,给出提示
console.log("您搜索过此物品");
删除数据使用splice()属性;
例二:搜索过的记录可以互相转换(备忘事件和过期事件)
html:中
<div>
<input type="text" [(ngModel)]="keyword" (keyup)="keyUp($event)">
<h3>待办事项</h3>
<ul>
<li *ngFor="let item of todolist; let key=index" [hidden]="item.status==1">
<input type="checkbox" [(ngModel)]="item.status">{{item.title}}
<button type="button" (click)="deletedata()">x</button>
</li>
</ul>
<h3>已办事项</h3>
<ul>
<li *ngFor="let item of todolist; let key=index" [hidden]="item.status==0">
<input type="checkbox" [(ngModel)]="item.status">{{item.title}}
<button type="button" (click)="deletedata()">x</button>
</li>
</ul>
</div>
ts:中
public keyword:string="";
public todolist:any[]=[];
keyUp(e){
if(e.keyCode == 13){
console.log(this.keyword);
// 先去重
if(!this.todoListHasKeyWord(this.todolist,this.keyword)){
this.todolist.push({title:this.keyword,status:0});
this.keyword="";
}else{
console.log("您已经搜索过此物品");
}
}
}
// 封装去重写法
todoListHasKeyWord(todolist:any,keyword:any){
if(!keyword) return false;
for(var i=0;i<todolist.length;i++){
if(todolist[i].title == keyword){
return true;
}
}
return false;
}
deletedata(key){
this.todolist.splice(key,1);
}
解析:
传入todolist(历史记录列表),keyword(输入框中的值)这两个值进入自定义的函数中,在接下来进行判断,因为todolist的title就是输入框中的值也就是验证
todolist.title ==keyword;在todolist(历史列表中)进行逐个排查 for( var i= 0;i<todolist.length;i++){todolist[i].title==keyword}如果为真,则就
返回true(真),if(!keyword) return false;判断里面是否存在和keyword相同的值,不存在返回false;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理