如何使用 *ngFor 和映射列表生成复选框
How to generate checkboxes using *ngFor and a list of maps
我有以下地图
.飞镖
List<Map<String, dynamic>> symptoms = [
{'name': 'Dizziness', 'checked': false},
{'name': 'Fainting', 'checked': false}
];
我在 中的 错误 尝试如下所示 html
.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>
我的问题如下:
- 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?
编辑 1
我现在看到复选框和标签使用以下内容:
<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>
但是,标签似乎在一行而复选框在另一行。我正在使用 bootstrap.min.css 并想知道这是否是主要原因。复选框也比预期的要大,如下所示:
干杯,谢谢
泰迪
您的 ngFor
语法不正确。表达式应该是“#binding of list”,而不是in。有关更详尽的解释,请参阅 。
此外,如果您想重复标签和复选框,则需要将模板移到 DOM 树的更高位置。为此,请使用扩展的 ngFor
语法。
最后,使用 ngModel
而不是绑定到 checked
- 属性的存在必须是 checked="checked",这不适合绑定到 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>
`
})
我有以下地图
.飞镖
List<Map<String, dynamic>> symptoms = [
{'name': 'Dizziness', 'checked': false},
{'name': 'Fainting', 'checked': false}
];
我在 中的 错误 尝试如下所示 html
.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>
我的问题如下:
- 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?
编辑 1
我现在看到复选框和标签使用以下内容:
<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>
但是,标签似乎在一行而复选框在另一行。我正在使用 bootstrap.min.css 并想知道这是否是主要原因。复选框也比预期的要大,如下所示:
干杯,谢谢 泰迪
您的 ngFor
语法不正确。表达式应该是“#binding of list”,而不是in。有关更详尽的解释,请参阅
此外,如果您想重复标签和复选框,则需要将模板移到 DOM 树的更高位置。为此,请使用扩展的 ngFor
语法。
最后,使用 ngModel
而不是绑定到 checked
- 属性的存在必须是 checked="checked",这不适合绑定到 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>
`
})