I tried to use BehaviorSubject, in my own small app which stores the state of the selected checkboxes. Here's the link to the app Stackblitz Code
I have a list of countries checkboxes (Mexico, Canada, USA, etc.) on a page whose checked state I need to maintain. For that, I am using an Angular Service with BehaviorSubject. Whenever I select few checkboxes and then click on the save button on the page, I pass the checkbox checked status data to the service, and the service then passes that data back to the component through the BehaviorSubject.
The component will only pass checkbox status data to the service if the apply button is clicked, but, when I check few checkboxes and then navigate to a different page (eg. home page) on the app using router link, and when I move back to the menu page with all the checkboxes, the BehaviorSubject from the service returns the checkboxes that were clicked. That is strange, isn't it? What am I missing here?
Note: I am calling storeData method only if the user clicks the save button. Even if I comment the call to the storeData method in save method, I see the same behavior. Does it have to do something with BehaviorSubject? I am using BehaviorSubject so that the service passes the previous data when the component loads and subscribes to the options$
Here's the code: component.html
<div class="countries" *ngFor="let item of data">
<input
[id]="item"
type="checkbox"
[checked]="selectedOption[item]"
[value]="item"
(change)="onToggle($event)"
/>
<label [for]="item">{{ item }}</label>
</div>
<button (click)="saveOptions()">Save</button>
component.ts
data = [
"India",
"Australia",
"USA",
"Brazil",
"Canada",
"South Africa",
"UK",
];
selectedOption = {};
constructor(private dataService: DataService, private router: Router) {}
ngOnInit(): void {
this.dataService.options$.subscribe((data) => {
console.log(data);
this.selectedOption = data;
});
}
onToggle(event) {
this.selectedOption[event.target.value] = event.target.checked;
}
saveOptions() {
this.dataService.storeData(this.selectedOption);
this.router.navigate(["/home"]);
}
data.service.ts
selectedOptions = {};
optionsAction = new BehaviorSubject<any>(this.selectedOptions);
options$ = this.optionsAction.asObservable();
constructor() {}
storeData(data) {
this.selectedOptions = data;
this.optionsAction.next(data);
}