How to compare a checkbox with my database value? | Angular

Viewed 231

How can I compare a dynamic created list of checkboxes with my database value?

If the value in my database is not null, its a checked box.

That´s the way how I generate my checkboxes. I already tried something with ngModel, but I have no idea how to handle this.

<div class="list-container">
    <ng-container *ngFor="let char of allATypes">
        <mat-checkbox [(ngModel)]="char.checked"> {{char.bezeichnung}} </mat-checkbox>
    </ng-container>
</div>

My goal is something like this pseudocode if(aType.allgemeinesMerkmal.bezeichnung) { char.checked = true) } How can I handle this?

2 Answers

You can do this by API hit:

<div class="list-container">
    <ng-container *ngFor="let char of allATypes">
        <mat-checkbox (click)="check_id_db(char.id)">
            {{char.bezeichnung}}
        </mat-checkbox>
    </ng-container>
</div>

In your .ts file, as you have injected service:

constructor(private apiService: ApiService) { }

Work to hit HTTP:

check_id_db(id){
    this.apiService.check_val(id).subscribe(res=>{
        console.log.(res);
    });
}

You're almost there, just make sure that you're binding the ngModel to the correct property.

  • Loop through the source array in the component template using *ngFor.
  • For each item, add a checkbox and bind it to the property that holds the checked indicator, using ngModel.
  • If you want to return the changed checkboxes (checked/unchecked) to the server again, you have to use two-way binding [(ngModel)]="....", otherwise you can only use one-way binding [ngModel]="..."

component.ts

// I used this static data, but you should use the data that comes from the server. 
allATypes = [
  {
    title: 'Test 1',
    enabled: true,
  },
  {
    title: 'Test 2',
    enabled: false,
  },
  {
    title: 'Test 3',
    enabled: true,
  },
];

onSubmit() {
  console.log(this.allATypes);
  // here you can send the updated data to the server.
}

component.html

<ng-container *ngFor="let item of allATypes">
  <mat-checkbox [(ngModel)]="item.enabled">{{ item.title }} </mat-checkbox>
</ng-container>
<button (click)="onSubmit()">Submit</button>

Here's a working StackBiltz demo.

Related