這篇筆記主要是以網上的一個視頻教程爲基礎,記錄視頻中的實踐操作,主要實現了一個類似於京東搜索和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>