1create service
ng g service url/servicename
2 localStorage
------------------------------------
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CommonService {
set(key: string, value?: string) {
localStorage.setItem(key, JSON.stringify(value))
}
get(): string[]{
var getjson = localStorage.getItem('historyList');
var obj = JSON.parse(getjson == null ? "": getjson);
return obj;
}
revome(key: string) {
localStorage.removeItem(key)
}
constructor() { }
}
--------------------------
component html
<ul *ngFor="let item of get_history()">
<li>{{item}}<button (click)="delTodo(item)">削除</button></li>
</ul>
<input type="text" #todo>
<button (click)="addTodo(todo.value)">追加</button>
————————————————————
component
import { Component, OnInit } from '@angular/core';
import { CommonService } from 'src/app/services/common.service';
@Component({
selector: 'app-testcomp',
templateUrl: './testcomp.component.html',
styleUrls: ['./testcomp.component.css']
})
export class TestcompComponent implements OnInit {
public com: any;
public historyList: any[] = [];
public keyword: string = "";
constructor(com: CommonService) {
this.com = com;
}
ngOnInit(): void {
}
get_history(): any[] {
return this.com.get("historyList");
}
addTodo(todo: string): void {
let back:string[] =this.com.get("historyList");
if (back == null || back.indexOf(todo) == -1) {
back.push(todo);
}
this.com.set("historyList", back);
}
delTodo(todo: string) {
let back: string[] = this.com.get("historyList");
for (let i= 0; i < back.length; i++) {
if (back[i] === todo) {
back.splice(i, 1);
}
}
this.com.set("historyList", back);
}
}
app moudle
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { TestcompComponent } from './components/testcomp/testcomp.component';
import { CommonService } from './services/common.service';
@NgModule({
declarations: [
AppComponent,
TestcompComponent
],
imports: [
BrowserModule
],
providers: [CommonService],
bootstrap: [AppComponent]
})
export class AppModule { }