简体   繁体   中英

How to set mat-checkbox as checked and unchecked using api response in Angular 6

I am new to angular 6, here I'm trying to set a mat-checkbox as checked and unchecked based on the API data.

but in my case it's not worked, almost I have tried all the way to change the state .but it not worked for me.

API Response :

{"Table":[{"BUY_NOW_STATUS":"false"},{"BUY_NOW_STATUS":"true"},{"BUY_NOW_STATUS":"false"},{"BUY_NOW_STATUS":"true"}]}

app.component.ts

assigning the response to the local variable as follows.

this.summary = data['Table'];

And I have checked whether I am getting data or not in the console and I got the response in the console as I expected.

aap.component.html

<div  *ngFor="let data of summary">
   <mat-checkbox [checked]="data.BUY_NOW_STATUS" class="mat-checkbox-inner-container">Buy now</mat-checkbox>
 </div>

currently, it shows as all the checkbox as checked.

can anyone help me to fix this.

before assigning please check the datatype of your BUY_NOW_STATUS coming from a server it should be boolean not string else convert the datatype to boolean

you have to use [(ngModel)] for 2 way binding data in angular.

to make this applicable use [(ngModel)]="data.BUY_NOW_STATUS"

this will also help you to store the current value of your checkbox which is true or false

after using [(ngModel)] there is no use to use [checked]

Use ngModel to set the values like below. And 'name ' property need to be set otherwise checkbox won't work properly..

<div  *ngFor="let data of summary; let i = index;">
   <mat-checkbox [(ngModel)]="data.BUY_NOW_STATUS" name="status{{i}}" class="mat-checkbox-inner-container">Buy now</mat-checkbox>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM