![]()
1 <div class="search">
2 <input type="text" [(ngModel)]="keyword"> <button (click)="search()">搜索</button>
3 </div>
4 <div class="list" *ngFor="let item of historyList; let key=index;">
5 <span>{{item}}-------<span (click)="delete(key)">X</span></span>
6 </div>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
historyList:Array<any>=[];//搜索记录
keyword:string='';//搜索关键词
constructor() { }
ngOnInit() {
}
search(){
console.log(this.keyword);
if(this.historyList.indexOf(this.keyword)==-1){ //如果这个关键词已经在搜索记录中,不再第二次显示,所以只有当这个关键词没有出现过才打印
this.historyList.push(this.keyword);
}
this.keyword=''; //打印出搜索记录后,清空输入框的值
}
delete(keyIndex){
alert(keyIndex);//当前删除按钮对应的索引
this.historyList.splice(keyIndex,1);//根据这个索引,从搜索记录中从当前索引开始删除一个元素,即删除当前索引代表的关键词
}
}