sasi
sasi

Reputation: 858

How to make a checkbox check dynamically based on a array of values in angular 6?

My ajax call result is like the following,

data : 
  0: {Address: "Delhi", EmailID: "[email protected]", MobileNo: 
"9876543210", Name: "Bravo", Date: "04/06/2008", …}
1: {Mode: "0"}
2: {Mode: "1"}
3: {Mode: "2"}
4: {Mode: "3"}
5: {Mode: "4"}

I can display the datas using,

 <p *ngIf="details">{{ details[0]?.EmailID }}</p>

But the modes which Im getting are the values of checkboxes. How can I make a checkbox selected based on the values which is returing from ajax call.

My checkbox code html is given following:

   <div class="custom-checkbox">
     <input type="checkbox" class="custom-control-input 
       [attr.id]="mode[i].id" [name]="mode[i].name"
       [checked]="(mode && (mode.indexOf(mode[i].id) !== -1))">
     <label class="custom-control-label" [attr.for]="mode[i].id"> 
       {{mode[i].name}}</label>
   </div>
   <div class="custom-control custom-checkbox custom-control-inline">
     <input type="checkbox" class="custom-control-input" 
       [attr.id]="mode[i+1].id" [name]="mode[i+1].name"
       [checked]="(mode && (mode.indexOf(mode[i+1].id) !== -1))">
     <label class="custom-control-label" [attr.for]="mode[i+1].id"> 
       {{mode[i+1].name}}</label>
   </div>

My ts file:

public mode = [
  { id: 0, name: 'Select All' },
  { id: 1, name: 'aaa' },
  { id: 2, name: 'bbb' },
  { id: 3, name: 'cccc' },
  { id: 4, name: 'dddd' },
];

Can somebody help me with this please?

Upvotes: 1

Views: 11217

Answers (1)

Syed Ali Taqi
Syed Ali Taqi

Reputation: 4974

You would need something like this:

<input type="checkbox" value="item.id" [attr.checked]="fooData.mode === item.id ? true : null" />

notice null here.

I have created a small Working Demo like your code.

Updated Demo with array of data.

Upvotes: 3

Related Questions