-1

I am calling the function below into ngoninit and binding a checkbox value with ngmodel. Here the problem is that the default checkbox is coming back as checked. I don't get where I am wrong.

Json format: [{subproducts:[{checked:true}}]]

<label for="checkbox" class="checkbox">  
  <input id="checkbox" type="checkbox" value=" 
  {{newsubProduct[0].product}}" [(ngModel)]="newsubProduct[0].checked" [ngModelOptions]="
  {standalone: true}" /> <i class="skin"></i><span> 
  {{ newsubProduct[0].product }}</span>
</label>

listproduct() {
this.Service.getData("some api").subscribe((d) => {
        let mydata = d;
        this.result = mydata;
        this.selProducts = this.result;
        for (var i = 0; i < this.selProducts.length; i++) {
            let p1 = this.selProducts[i].subProducts.filter(p => p.checked);
            if (!_.isEmpty(p1)) {
                let p2 = p1.filter(p => {
                    if (p.checked) {
                        var checked = p.checked;
                        var product = p.backEndName;
                        this.newsubProduct.push({
                            checked: checked,
                            product: product
                        });
                    }
                });
            }

        }

    },
    err => {
        this.result = err;
    });}

The problem is that the checkbox is checked, I expect it to be unchecked.

Christian
  • 4,902
  • 4
  • 24
  • 42
DharamChauhan
  • 109
  • 1
  • 1
  • 11

1 Answers1

0

We can see from your comment, that your data looks like:

[ { "id":1, "subProducts":[ { "id":100, "checked":"false", "backEndName":"DDA" } ] } ]

So what we are seeing is that your get string value, not boolean. If you have access to the api, I would suggest that make the change there to return an actual boolean, not a string value. But if you can't do that change, you need to give the checkbox the boolean value. That can be done like here.

So make the following change:

this.newsubProduct.push({
  checked: (checked === 'true'),
  product: product
});

Now it should work: STACKBLITZ

AT82
  • 71,416
  • 24
  • 140
  • 167