【问题标题】:Saving checkbox selected when page is reloaded or visited later in Angular稍后在 Angular 中重新加载或访问页面时选中保存复选框
【发布时间】:2019-11-11 09:25:25
【问题描述】:

我的组件中有一个复选框:

<input (change)="fieldChange($event)" type="checkbox" />

我希望在您稍后访问此组件或重新加载页面时仍选中/取消选中它。所以它基本上需要保存,我猜?对 Angular 非常陌生,搜索了 2 个小时,但没有发现任何工作。

这是我目前的打字稿:

  public fieldChange(values: any){
    if (values.currentTarget.checked){
      console.log('hi');
    }
  }

我发现这是有效的,但它也需要取消选中并保存。有人可以帮帮我吗?

【问题讨论】:

  • 使用本地存储
  • 您也可以将其存储在cookie中。

标签: angular checkbox


【解决方案1】:

您可以使用 cookie 来存储此类小型配置。首先将输入绑定到一个变量。

component.html

<input (change)="fieldChange($event)" type="checkbox" [(ngModel)]="isChecked"/>

编写两个函数来写入和读取 cookie 并在服务中使用它们。

cookie.service.ts

getCookie(name : string): string{
    const value = "; " + document.cookie;
    const parts = value.split("; " + name + "=");    
    if (parts.length == 2) {
        return parts.pop().split(";").shift();
    }
}

setCookie(name : string, val : string){
    const date = new Date();
    const value = val;
    date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = name+"="+value+"; expires="+date.toUTCString()+"; path=/";
}

在组件初始化时读取 cookie。在更改复选框值时,重写 cookie 值。

component.ts

ngOnInit(){
    // Other code
    isChecked = this.cookieService.getCookie('isChecked');
}

public fieldChange(values: any){
    // Other code
    this.cookieService.setCookie('isChecked',isChecked);
}

【讨论】:

    猜你喜欢
    • 2020-03-11
    • 2015-03-28
    • 2021-03-01
    • 2023-03-14
    • 2013-02-12
    • 2016-08-23
    • 2015-10-18
    • 2010-09-22
    相关资源
    最近更新 更多