实现 仿京东的搜索历史 demo
首先我们先创建一个组件
ng g component components/search
创建完组件之后,在app.component.html内引入组件,之后在search.component.ts里面来写一下搜索框
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
public keywords:string = '' //搜索关键字
public historyList:any[] = []
constructor() {
}
ngOnInit() {
// 每次组件刷新都会加载这个生命周期函数
console.log('每次组件刷新都会加载这个生命周期函数');
}
}
doSearch(){
console.log(this.keywords, 'this.keywords');
//判断搜索内容是否重复,重复的话就不添加进去
if(this.historyList.indexOf(this.keywords)=== -1){
//把搜索内容添加进数组
this.historyList.push(this.keywords)
console.log(this.historyList);
//清空搜索框
this.keywords = ''
}
}
doDel(key){
//删除搜索历史
this.historyList.splice(key,1)
this.storage.set('searchResult',this.historyList)
}
}
实现 待办事项 demo
同样是先创建一个组件
ng g component components/toDoList
之后写逻辑toDoList.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-to-do-list',
templateUrl: './to-do-list.component.html',
styleUrls: ['./to-do-list.component.scss']
})
export class ToDoListComponent implements OnInit {
public keywords: string = ''
public toDoList: any[] = []
constructor() { }
ngOnInit() {}
doAdd(e) {
if (e.keyCode === 13) {
if (!this.toDoListHasKeywords(this.toDoList, this.keywords)) {
this.toDoList.push({
title: this.keywords,
status: 0 //0表示待办事项,1表示已完成事项
});
this.keywords = ''
}else{
alert('数据已经存在')
this.keywords = ''
}
}
}
doDel(key) {
this.toDoList.splice(key, 1)
}
toDoListHasKeywords(toDoList: any, keywords: any):any {
if(!keywords) return false
for (let i = 0; i < toDoList. length; i++) {
if (toDoList[i].title === keywords) {
return true
}
return false
}
}
}
toDoList.component.html
<div class="toDoList">
toDoList :<input type="text" placeholder="请输入待办事项" [(ngModel)]="keywords" (keyup)="doAdd($event)" >
<hr>
<h2>
待办事项
</h2>
<ul>
<li *ngFor="let item of toDoList let key = index " [hidden]="item.status==1">
<input type="checkbox" [(ngModel)]="item.status" />{{item.title}} -------- <button (click)="doDel(key)">删除</button>
</li>
</ul>
<h2 class="complete">
已完成事项
</h2>
<ul>
<li *ngFor="let item of toDoList let key = index " [hidden]="item.status==0">
<input type="checkbox" [(ngModel)]="item.status" />{{item.title}} -------- <button (click)="doDel(key)">删除</button>
</li>
</ul>
</div>
其他的样式自己调一下就OK了~