Home > Back-end >  make checkboxes checked depending on database values in angular
make checkboxes checked depending on database values in angular

Time:10-19

I am showing multiple checkboxes depending on database fetched values. And I need to make them checked from stored values.

Template code

 <div >
                <div >
                  <label >Type of events <b style="color: red">*</b></label>
                  <div >
                    <div   *ngFor="let event of EventTypes index as i">
                      <input type="checkbox" 
                      [name] = "'EventType_' event.id" 
                      [value]="event.id" 
                      (change)="onCheckboxChange($event)"
                      
                      />
                      <div   >
                        <label> {{ event.name | titlecase }} </label>
                      </div>
                    </div>
                  </div>
                  <div  *ngIf="submitted && this.form.controls['checkArray'].errors?.required" >
                    Event type is required, select atleast one value.
                  </div>

                </div>
              </div>

component code

EventTypes: any = [];
  selectedEventIds:any = [];
...
 this.userService.getEventType().subscribe((data) => {
      console.log(data);
      this.EventTypes = data.data;
    });
....
 if (results['status'] === true) {

for (let event_type of results.data.event_type) {
              this.selectedEventIds.push(event_type.event_type_id);
            }
...

First I am showing database default elements in checkboxes by iterating EventTypes . And storing user selected value. I am fetching those selected values in selectedEventIds. Now I need to make checkboxes checked if id and fetched value matches.

I tried by adding [attr.checked]="selectedEventIds[i] === event.id ? true : null" but its not working.

Somehow I need to check each value of selectedEventIds with current event.id. How I can do that in angular? Is there any other way to make checkbox checked depending on database values?

Please guide and help. Thanks in advance.

CodePudding user response:

You need to add a function & that function will check this event id is present in selectedEventIds array Please try below code.

[attr.checked]="isChecked(event.id)"

isChecked(eventId){
  return this.selectedEventIds.indexOf(eventId)>-1 ? true : null
}
  • Related