I’m working in a Angular project (version 16) and I’d like to build a dialog modal with a "do not show again" checkbox.
The process would be this one :
- a user visits the web application. At his first connection, a dialog modal appears with the "do not show again" checkbox
- the user reads the content of the modal and chooses to check the checkbox
- if the user visits the web app some minutes later, the dialog modal no longer appear because the browser stores the previous choice of user to "do not show again"
I read some stuff about the LocalStorage fonctionnality but don’t know how to build it in Angular.
Here is my code for the moment :
TS :
openDialog() {
const dialogRef = this.dialog.open(ModalDialogComponent);
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog result: ${result}`);
});
}
HTML (Angular-Material UI) :
<h2 mat-dialog-title>My dialog modal</h2>
<mat-dialog-content class="mat-typography">
<mat-tab-group>
<mat-tab label="First">First</mat-tab>
<mat-tab label="Second">Second</mat-tab>
</mat-tab-group>
<mat-checkbox class="example-margin">Do not show again</mat-checkbox>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Cancel</button>
<button mat-button [mat-dialog-close]="true" cdkFocusInitial>Install</button>
</mat-dialog-actions>
Have you any ideas to complete this ?
Any help would be thankly appreciated, thanks.
3
Answers
You can save to local storage a string value when the user clicks the "do not show again" checkbox
and before opening the modal check in local storage if that value is saved
Code example:
Do you just need to know how to access localStorage? If that is the case, the syntax is just this:
To set a localStorage item:
To get a localStorage item:
Keep in mind that localStorage items are stored as strings, so you would need to do some conversion to convert the string to a boolean value. Something like this:
On first load, if the localStorage item is not present, then the dialog will be shown. If the user clicks on the checkbox, just set the localStorage item to ‘no’ or something like that.
On initialization you have to load the boolean firstVisit then you check if it is true, it means you need to show the dialog
Your main component:
And you also need to store the validation value if the user clicks accept
Basically, you can store data in local storage using:
Read data from local storage using: