Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i save the user selected option after refresh

i’m using a mat-option and the default value is 10 but the user can change this number from the option list, how can i save his variable if he select let’s say 25 and even after he refresh the page the default value is his choice.

I’ve tried localstorage but the value resets after refreshing the page

<div class="col-md-auto">
                <mat-form-field style="width: 100px;">

                <mat-label>Elements on page</mat-label>
                <mat-select style="width: 100px" [(ngModel)]="limit">
              
                  <mat-option value="10">10</mat-option>
                  <mat-option value="25">25</mat-option>
                  <mat-option value="50">50</mat-option>
                  <mat-option value="100">100</mat-option>
                  
                </mat-select>
               
              </mat-form-field>
            </div>

and my typescript is like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

limit:any = '10';

ngOnInit(): void {
    localStorage.setItem("limit", localStorage.getItem("limit"))
  
  }

>Solution :

What you want when the page is loaded is set the localStorage value inside your limit parameter :

ngOnInit(): void {
   this.limit = localStorage.getItem("limit");
}

Then, you must catch when user change value to set it inside the localstorage :

changed(): void {
    localStorage.setItem("limit", this.limit)
  }

And update your HTML :

<mat-select (change)="changed()" style="width: 100px" [(ngModel)]="limit">
             
                  <mat-option value="10">10</mat-option>
                  <mat-option value="25">25</mat-option>
                  <mat-option value="50">50</mat-option>
                  <mat-option value="100">100</mat-option>
                  
                </mat-select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading