Issue
Newbie to front-end world...I have a use case specifically in which i need to save toggle state on or off depending on user choice.
- If a user has previously selected toggle ON then i need to make sure that toggle is on for that particular user next time he or she visits the page.
- if a user has previously selected toggle OFF then i need ot make sure that toggle is off for that particular user next time her or she visits the page.
Below is my html implementation
<div class="toggle-checkbox">
<label class="showLabel" for="show">Toggle on or off :</label>
<label class="toggle">
<input class="toggle-input" id="togBtn" type="checkbox" (click)="validate()" />
<span class="toggle-label" data-off="OFF" data-on="ON"></span>
<span class="toggle-handle"></span>
</label>
</div>
</div>
In the external typescript file i am trying to save the state like this -
validate(){
var input = document.getElementById('togBtn') as HTMLInputElement;
if (input.checked) {
localStorage.setItem('togBtn', 'true');
} else {
localStorage.setItem('togBtn', 'false');
}
}
tried this in typescript file but everytime i tried to re-visit the page with same request information then the toggle information is not saved for that user. I would appreciate any help.
Solution
You can add a function to check the localStorage when the page loads and set the initial state of the toggle accordingly.
HTML:
<div class="toggle-checkbox">
<label class="showLabel" for="show">Toggle on or off :</label>
<label class="toggle">
<input class="toggle-input" id="togBtn" type="checkbox" (click)="validate()" />
<span class="toggle-label" data-off="OFF" data-on="ON"></span>
<span class="toggle-handle"></span>
</label>
</div>
TypeScript:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
ngOnInit() {
// Check the localStorage for the saved toggle state
const toggleState = localStorage.getItem('togBtn');
// If a state is found, set the toggle accordingly
if (toggleState === 'true') {
this.setToggle(true);
} else {
this.setToggle(false);
}
}
validate() {
const input = document.getElementById('togBtn') as HTMLInputElement;
if (input.checked) {
localStorage.setItem('togBtn', 'true');
} else {
localStorage.setItem('togBtn', 'false');
}
}
// Function to set the toggle state
setToggle(state: boolean) {
const input = document.getElementById('togBtn') as HTMLInputElement;
input.checked = state;
}
}
Answered By - Ale_Bianco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.