Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list of checkboxes with ngFor Angular

I have a list of objects that's structured like this:

[{item},{item},{item}]

I'm trying to create a list of checkboxes with angular out of this list like this:

<form>
     <input *ngFor="let object of objects" type="checkbox"> {{object.name}}
</form>

The checkboxes themselves do show up, but I can't get the name of the object to show with each checkbox. What am I doing wrong?

like image 268
sander Avatar asked Sep 02 '25 09:09

sander


2 Answers

You can use check box with *ngFor as follows.

<form>
   <div *ngFor="let object of objects">
      <input type="checkbox" [checked]="object.checked"> {{object.name}}
   </div>
</form>
like image 136
Akj Avatar answered Sep 04 '25 23:09

Akj


The object variable only exist in the context of the ngForOf, in your case, this is the context of the <input> element.

You could wrap the <input> inside of a ng-container element, and bind the ngForOf to the last. Like this:

<form>
   <ng-container *ngFor="let object of objects">
      <input type="checkbox"> {{object.name}}
   <ng-container>
</form>

With this approach, the generated HTML is the same, as the ng-container element is stripped away.

like image 30
Jota.Toledo Avatar answered Sep 04 '25 22:09

Jota.Toledo