列出搜索过的数据(类似京东顶部搜索框)

tip: 只要进行数据绑定,一定要先检查是否在app_module.ts中进行过formsModule的数据引入,如果没有进行引入,在数据绑定的时候会出现报错

例一:京东搜索,历史记录

html:

    

      

      

      

            

  • {{item}}

              

            

  •       

    

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:中

   

    

    

待办事项

    

          

  •         {{item.title}}

            

          

  •     

    

已办事项

    

          

  •         {{item.title}}

            

          

  •     

  


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

      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

  返回true(真),if(!keyword) return false;判断里面是否存在和keyword相同的值,不存在返回false;

你可能感兴趣的:(列出搜索过的数据(类似京东顶部搜索框))