I have the following map
List<Map<String, dynamic>> symptoms = [
{'name': 'Dizziness', 'checked': false},
{'name': 'Fainting', 'checked': false}
];
My incorrect attempt in html is shown below
<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:
- The label for each checkbox should be "symptom['name'] - how do I integrate this in the *ngFor?
- How can I determine that a specific checkbox was selected?
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:
Cheers, and thanks Teddy
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With