Why can't my mat checkbox update the correct value?

1.1k Views Asked by At

in my app I'm using a BehaviourSubject which I toggle value to update a MatCheckbox. only problem is that the value doesn't get updated to the correct value, in this StackBlitz the value of isChecked is supposed to be setted instantely to false each time I check the checkbox but the value don't get updated on the checkbox.

I've been looking over internet without seeing an answer to my case

EDIT:

for the moment I've been able to achieve what I want by adding setTimeout(() => this.isChecked = false, 500) in the subscribe method.

3

There are 3 best solutions below

1
Suneel Kumar On

I check your code, you are updating isChecked value twice, one inside the change() method & second inside the subscribe() method, what kind of implementation you have done so far, it's working fine with respect to that.

Now what you want try to achieve? please let me know! If your intension is just to update the isChecked value, then change() is enough for that,

1
Juan Vicente Berzosa Tejero On

Here is your same code with some changes, working:

StackBlitzSolutionWorking

Basically, I did change the html:

<mat-checkbox [checked]="isChecked" (change)="change($event)">Hello</mat-checkbox>

and in TS:

import { MatCheckboxChange } from '@angular/material/checkbox/checkbox';
...

change(event: MatCheckboxChange) {
    this.isChecked = event.checked;
    this.test.bool.next(this.isChecked);
  }

  constructor(private test: TestService) {
    this.test.bool.subscribe(bool => {
      console.log('this.isChecked:', this.isChecked);
      console.log('bool:', bool);
      // if (bool) this.isChecked = false;
    });
  }

The problem was that with the sentence 'if (bool)' isChecked always was 'false': when the check wasn't checked, it was false, and when the check was checked, as bool===true, it turned into false as well.

3
Micah C On

Log the event in the function you're calling. The subscribe is setting it to false.

import { Component, VERSION } from '@angular/core';
import { TestService } from './test.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [TestService]
})
export class AppComponent {
  isChecked = false;

  constructor(private test: TestService) {
  }

  name = 'Angular ' + VERSION.major;

  get bool(){
    return this.test.bool
  }

  change(value){
    this.isChecked = value;
    console.log(this.isChecked);
  }
}