R-b-n
R-b-n

Reputation: 513

Saving checkbox selected when page is reloaded or visited later in Angular

I have a checkbox in my component:

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

I want it to still be checked/unchecked once you visit this component later or reload the page. So it basically needs to be saved, I guess? Very new to Angular and searched for 2 hours but found nothing working.

This is the typescript I have so far:

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

And I see that this is working, but it also needs to be unchecked and saved. Can someone please help me?

Upvotes: 1

Views: 1246

Answers (1)

MonkeyScript
MonkeyScript

Reputation: 5121

You can use cookies to store such small configurations. First bind the input to a variable.

component.html:

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

Write two functions to write and read cookies and use them in a service.

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=/";
}

Read the cookie when component initializes. On changing checkbox value, rewrite the cookie value.

component.ts:

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

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

Upvotes: 1

Related Questions