How to generate checkboxes using *ngFor and a list of maps

14,925

Your ngFor syntax is incorrect. The expression should be "#binding of list", not in. See Mark's answer for a more elaborate explanation.

Also if you want to repeat the label and the checkbox, you need to move the template higher up the DOM tree. For this, use the expanded ngFor syntax.

Finally, use ngModel instead of binding to checked - the existence of the attribute must be checked="checked" which does not make it ideal for binding to a Boolean.

@Component({
  selector: 'my-app',
  directives: [NgFor],
  template: `{{title}} <br />
  <form>
  <div class = "form-group">
        <template ngFor #symptom [ngForOf]="symptoms">
        <div class = "form-control">
          <label for="symptom" >{{symptom.name}}</label>
            <input
              type = "checkbox"
              ngControl="symptom"
              [(ngModel)]="symptom['checked']" />
        </div>
        </template>
  </div>
  </form>
  `
})

Demo Plnker

Share:
14,925
st_clair_clarke
Author by

st_clair_clarke

Updated on June 19, 2022

Comments

  • st_clair_clarke
    st_clair_clarke almost 2 years

    I have the following map

    .dart

    List<Map<String, dynamic>> symptoms = [
      {'name': 'Dizziness', 'checked': false},
      {'name': 'Fainting', 'checked': false}
    ];
    

    My incorrect attempt in html is shown below

    .html

    <div class = "form-group">
            <div class = "form-control"
                 ngControl = "symptoms">
              <label for="symptom" >Symptoms</label>
                <input
                  type = "checkbox"
                  *ngFor = "#symptom in symptoms"
                  [checked]="symptom['checked']"/>
    
            </div>
      </div>
    

    My issues are as follows:

    1. The label for each checkbox should be "symptom['name'] - how do I integrate this in the *ngFor?
    2. How can I determine that a specific checkbox was selected?

    EDIT 1

    I am now seeing the checkbox and the label using the following:

      <div layout = "row"
           layout-align = "center"
           class = "form-group"
           *ngFor = "#s of symptoms">
        <label>{{s['name']}} </label>
        <input
            type = "checkbox"
            [checked] = "s['checked']"
            class = "form-control"/>
      </div>
    

    However, the label seems to be on one row and the checkbox on another. I am using bootstrap.min.css and wonder if this is the main cause. The checkboxes are larger than expected too as shown below:

    enter image description here

    Cheers, and thanks Teddy