angular demo本地存储和服务——todolist

demo:todolist,使用服务创建公共函数,并进行数据本地化存储
待解决:checkbox进行双向绑定的时候如如指定值?不局限于true和false?

涉及知识点:

  • 数组操作:unshift向数组头部添加,push尾部追加
  • 删除数组元素:todoList.splice(index,1),从索引index处开始,删除1个元素
  • loclaStorage进行浏览器本地存储:localStorage.setItem(key,JSON.stringify(value));
  • 服务:组件中可以调用服务中的函数,反过来则不行

1.创建服务组件

ng g service services/storage

2.app.module.ts 里面引入创建的服务

import {
      NgModule } from '@angular/core';  // 实现表单元素的双向数据绑定
// 引入创建的服务
import {
      StorageService } from './services/storage.service';

@NgModule({
     
  declarations: [
    AppComponent,
    FormComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,    // 引入
  ],
  providers: [StorageService,],  // 依赖注入服务
})

3.在服务中定义公共的函数:storage.service.ts

import {
      Injectable } from '@angular/core';

@Injectable({
     
  providedIn: 'root'
})
export class StorageService {
     

  constructor() {
      }

  set(key:string,value:any){
     
    // 存入浏览器的localStorage
    localStorage.setItem(key,JSON.stringify(value));
  };

  get(key:string){
     
    // 拿到的可能是json格式的对象
    return JSON.parse(localStorage.getItem(key));
  };
  
  remove(key:string){
     
    localStorage.removeItem(key);
  };
}

4.todo-list.component.ts

import {
      Component, OnInit } from '@angular/core';

// 在组件中引入服务
import {
      StorageService } from '../../services/storage.service';

@Component({
     
  selector: 'app-todo-list',
  templateUrl: './todo-list.component.html',
  styleUrls: ['./todo-list.component.css']
})
export class TodoListComponent implements OnInit {
     

  public keyword: string;
  public todoList: any[]=[];

  // 在组件的构造器中注册服务
  constructor(private storage: StorageService) {
      }

  // 在初始化方法中读取localStorage
  ngOnInit() {
     
    var todoList:any=this.storage.get('todoList');
    if(todoList){
     
      this.todoList=todoList;
    }
  }

  // 检查todoList中的task是否重复
  checkRepeat(todoList: any,keyword: string){
     
    for(var i=0;i<todoList.length;i++){
     
      if(todoList[i].task==keyword){
     
        return true
      };
    };
    return false
  }

  // input框回车后添加task
  doAdd(e: any) {
     
    if(e.keyCode==13){
     
      var isRepeat=this.checkRepeat(this.todoList,this.keyword)
      if(isRepeat){
     
        alert(this.keyword+"已存在");
      }else{
     
        this.todoList.unshift(    // unshift向数组头部添加,push追加
          {
     
            "task": this.keyword,
            "status": false,
          }
        );
        this.storage.set('todoList',this.todoList);
      }
      this.keyword="";
      console.log(this.todoList);
    }
  }

  // 删除task
  delTask(index: any){
     
    this.todoList.splice(index,1)
    this.storage.set('todoList',this.todoList);
  }

  checkboxChange(){
     
    this.storage.set('todoList',this.todoList);
  }
}

5.todo-list.component.html

<div>
    <h1>todoList
        <input type="text" class="form-input" [(ngModel)]="keyword" (keyup)="doAdd($event)">
    h1>

    <hr>

    <h3>代办事项h3>
        
        <p *ngFor="let item of todoList;let key=index;" [hidden]="item.status">
            
            
            <input type="checkbox" [(ngModel)]="item.status" (change)="checkboxChange()">
            {
    {item.task}} ------ <button (click)="delTask(key)">Xbutton>
        p>
    <hr>

    <h3>已完成事项h3>
        <p *ngFor="let item of todoList;let key=index;">
            
            <span *ngIf="item.status">
                <input type="checkbox" [(ngModel)]="item.status" (change)="checkboxChange()">
                {
    {item.task}} ------ <button (click)="delTask(key)">Xbutton>
            span>
        p>
div>

6.效果
angular demo本地存储和服务——todolist_第1张图片

参考:https://www.bilibili.com/video/av59049211?from=search&seid=485997827014437418

你可能感兴趣的:(web前端,angular)