这篇笔记主要是以网上的一个视频教程为基础,记录视频中的实践操作,主要实现了一个类似于京东搜索和toDoList的操作,其中包括的知识点主要是Angular组件如何调用服务,以及通过服务实现Angular前端数据的持久化。
先看最终的效果,说明,这个只是根据视频的一个Angular的示例,前端的样式几乎没有,重点是学习Angular的知识点。
在第一个搜索demo中,输入框中每次输入内容后,点击搜索,则下面的历史列表中会记录搜索的历史,当然也可以删除,同时数据会记录到localStorage中,页面刷新后仍然可以看到。
第二个toDoList示例中,在输入框中输入代办事项后,回车,则在代办列表中多了条记录,勾选复选框后,代办事项变更为已办事项,同样数据会保存在localStorage中,页面刷新后,数据依然可看。

1、创建项目及组件
ng new angulardemo
ng g c demo/search
ng g c demo/todolist
2、编写search组件代码,这里直接贴代码:
search.component.css
h2{
text-align: center;
}
.search{
width: 400px;
margin: 20px auto;
}
.search input{
margin-bottom: 20px;
width: 300px;
height: 30px;
}
.search button{
width: 80px;
height: 32px;
}
.search ul li{
list-style-type: none;
}
search.component.ts
import { Component, OnInit } from '@angular/core';
import {StorageService} from '../services/storage.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
public keywords = '';
public historyList: any[] = [];
constructor(public storage: StorageService) { }
ngOnInit() {
console.log('页面每次刷新的时候会触发');
const searchlist = this.storage.get('searchlist');
if (searchlist) {
this.historyList = searchlist;
}
}
// 搜索
doSearch() {
if (this.historyList.indexOf(this.keywords) === -1) {
this.historyList.push(this.keywords);
this.storage.set('searchlist', this.historyList);
}
this.keywords = '';
console.log(this.keywords);
}
// 删除
deleteHistory(key) {
this.historyList.splice(key, 1);
this.storage.set('searchlist', this.historyList);
}
}
search.component.html
<h2>京东搜索</h2>
<div class="search">
<input type="text" [(ngModel)]="keywords"> <button (click)="doSearch();">搜索</button>
<hr>
<ul>
<li *ngFor="let item of historyList;let key=index" >{{item}}---<button (click)="deleteHistory(key);">✘</button></li>
</ul>
</div>
3、创建服务:storage.service
ng g s services/storage
storage.service.ts
import { Injectable } from '@angular/core';
import {__values} from 'tslib';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() { }
// 获取数据
get(key: any) {
return JSON.parse(localStorage.getItem(key));
}
// 设置数据
set(key: any, value: any) {
localStorage.setItem(key, JSON.stringify(value));
}
// 删除数据
remove(key: any) {
localStorage.removeItem(key);
}
}
4、编写todolist组件代码
todolist.component.css
h2{
text-align: center;
}
.todolist{
width: 400px;
margin: 20px auto;
}
.form_input{
margin-bottom: 20px;
width: 300px;
height: 30px;
}
/*.todolist button{*/
/*width: 80px;*/
/*height: 32px;*/
/*}*/
.todolist ul li{
list-style-type: none;
line-height: 40px;
}
todolist.component.ts
import { Component, OnInit } from '@angular/core';
import {StorageService} from '../services/storage.service';
@Component({
selector: 'app-todolist',
templateUrl: './todolist.component.html',
styleUrls: ['./todolist.component.css']
})
export class TodolistComponent implements OnInit {
public keywords = '';
public todoList: any[] = [];
constructor(public storage: StorageService) { }
ngOnInit() {
const todolist = this.storage.get('todolist');
if (todolist) {
this.todoList = todolist;
}
}
doAdd(e) {
if (e.keyCode === 13) {
// 回车
const fla = this.todoListHasKey(this.todoList, this.keywords);
if (!fla) {
this.todoList.push({
title: this.keywords,
status: 0 // 0代表待办,1代表已完成
});
this.storage.set('todolist', this.todoList);
} else {
alert('数据已经存在');
}
this.keywords = '';
}
}
deleteData(key) {
this.todoList.splice(key, 1);
this.storage.set('todolist', this.todoList);
}
todoListHasKey(todolist: any, key: any) {
// 异步,会存在问题
// todolist.forEach(value => {
// if (value.title === key) {
// return true;
// }
// })
for (let i = 0; i < todolist.length; i++) {
if (todolist[i].title === key) {
return true;
}
}
return false;
}
checkboxChange() {
this.storage.set('todolist', this.todoList);
}
}
todolist.component.html
<h2>toDoList</h2>
<div class="todolist">
<input class="form_input" type="text" [(ngModel)]="keywords" (keyup)="doAdd($event);">
<hr>
<h3>待办事项</h3>
<ul>
<li *ngFor="let item of todoList;let key=index" [hidden]="item.status ==1">
<input type="checkbox" [(ngModel)]="item.status" (change)="checkboxChange();">{{item.title}}---<button (click)="deleteData(key);">✘</button>
</li>
</ul>
<hr>
<h3>已完成事项</h3>
<ul>
<li *ngFor="let item of todoList;let key=index" [hidden]="item.status ==0">
<input type="checkbox" [(ngModel)]="item.status" (change)="checkboxChange();">{{item.title}}---<button (click)="deleteData(key);">✘</button>
</li>
</ul>
</div>
5、app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { SearchComponent } from './demo/search/search.component';
import { TodolistComponent } from './demo/todolist/todolist.component';
import { StorageService } from './demo/services/storage.service';
@NgModule({
declarations: [
AppComponent,
SearchComponent,
TodolistComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.module.html
<!--The content below is only a placeholder and can be replaced.-->
<!--<app-my-com-name></app-my-com-name>-->
<!--<app-home></app-home>-->
<router-outlet></router-outlet>
<app-search></app-search>
<br>
<br>
<br>
<br>
<br>
<br>
<app-todolist></app-todolist>
1650



被折叠的 条评论
为什么被折叠?



