Search code examples
angular6angular7angular8angular9

checkbox should remains checked after refresh the page refresh


So here I'm using checkbox to hide and show templates. I just want code that will make checkbox remains checked after page refresh in angular 9 .Please help me.


Solution

  • You can do 2 things:

    1. Use RxJS and as soon as the checkbox is checked, you can use Behavior Subject to store the data and on reload or refresh event, read the behavior subject and patch the value

    2. Use sessionStorage, and do the same. As soon as its checked, store it in sessionStorage, on reload, try to read from sessionStorage and patch the value again.

    Implementation:

    // Using session storage
    
    someForm.controls.checkboxFormControl.valueChanges.subscribe(
      data => {
        if (data) {
            sessionStorage.setItem('checkboxChecked', true)
        }
    })
    
    onRefreshEvent() {
     let sessionStorageValue = sessionStorage.setItem('checkboxChecked'); 
     if (sessionStorageValue && (sessionStorageValue === true)) {
        this.someForm.contols.checkBoxControl.patchValue(true)
     }
    }
    
    
    //// Same with Behavior Subject as well
    
    // Create a Behavior Subject in your Service file
    checkboxCheckedSource: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
    checkBoxObservable: Observable<boolean> = this.checkboxCheckedSource.asObservable();
    
    setCheckboxValue(checked: boolean) {
      this.checkboxCheckedSource.next(checked);
    }
    
    getCheckboxValue(): Observable<boolean> {
      return checkBoxObservable;
    }
    
    // In your component.ts file
    
    someForm.controls.checkboxFormControl.valueChanges.subscribe(
      data => {
        if (data) {
            this.yourService.setCheckboxValue(true)
        }
    })
    
    onRefreshEvent() {
      this.yourService.getCheckboxValue().subscribe(checked => {
        if (checked) {
           this.someForm.contols.checkBoxControl.patchValue(true);
        }
      })
    }
    

    If its only one checkbox, i would prefer the sessionStorage way of doing it, else if you are storing a lot of checkboxes use BehaviorSubject!!