3

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?

Roy
  • 7,811
  • 4
  • 24
  • 47
sander
  • 1,426
  • 4
  • 19
  • 46

4 Answers4

6

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>
Akj
  • 7,038
  • 3
  • 28
  • 40
2

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.

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
0

You need to put *ngFor on a container to make the range variable be visible inside it. Here I have used div, but you can use anything you want.

<form>
   <div *ngFor="let object of objects">
      <input type="checkbox"> {{object.name}}
   <div>
</form>
Roy
  • 7,811
  • 4
  • 24
  • 47
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • It works, but it does create some boilerplate. I guess this is the only way to go. Do you think my example didn't work because Angular didn't have the access to the object.name variable? – sander Jul 02 '18 at 07:19
  • Yes, outside `input` it is not visible. – Suren Srapyan Jul 02 '18 at 07:20
0

I had to ensure the for attribute in the label was the same as the input id:

See snippet here

 <div class="m-checkbox-list">
   <label *ngFor="let detectionSource of detectionSources" for="detectionSource_{{detectionSource.id}}" class="m-checkbox">
    <input id="detectionSource_{{detectionSource.id}}" type="checkbox" name="detectionSource_{{detectionSource.name}}" [(ngModel)]="detectionSource.isSelected">
                                    {{detectionSource.name}}
    <span></span>
   </label>
 </div>
Eamon
  • 51
  • 1
  • 4