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>
        <!-- hidden属性:根据task的status决定是否隐藏 -->
        <p *ngFor="let item of todoList;let key=index;" [hidden]="item.status">
            <!-- checkbox进行双向绑定的时候如如指定值?不局限限于true和false? -->
            <!-- checkbox绑定change事件,变更localStorage中的数据 -->
            <input type="checkbox" [(ngModel)]="item.status" (change)="checkboxChange()">
            {{item.task}} ------ <button (click)="delTask(key)">X</button>
        </p>
    <hr>

    <h3>已完成事项</h3>
        <p *ngFor="let item of todoList;let key=index;">
            <!-- 一个标签中不能同时使用ngfor和ngif -->
            <span *ngIf="item.status">
                <input type="checkbox" [(ngModel)]="item.status" (change)="checkboxChange()">
                {{item.task}} ------ <button (click)="delTask(key)">X</button>
            </span>
        </p>
</div>

6.效果
在这里插入图片描述

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值