我正在使用带有复选框的Angular 5应用程序 . 我有来自数据库的数据,然后映射到javaScript对象 . 我正在尝试配置“已选择”值,但无法执行此操作 . 在我的结果中,我检查了所有应该是的盒子 .
在下面的代码中,选项:[] - >'optionSelected'定义,如果选择值为true或false,
生成的模式如下;
模板
<div *ngSwitchCase="'checkbox'"> <small>checkbox</small>
<div *ngFor="let opt of question.options" >
<label class="container-vertical"> {{opt.value}}
<input type="checkbox" [formControlName]="question.key" [name]="opt.name" [value]="opt.key" [checked]="opt.optionSelected" />
<span class="checkmark2"></span>
</label>
</div>
</div>
也尝试使用ngModel,因为在我的组件中,属性'value'包含所选键的id,但最终结果仍然检查所有框
<input type="checkbox" [formControlName]="question.key" [name]="opt.name" [value]="opt.key" [(ngModel)]="question.value" />
组件
else if(questionElementType=="checkbox")
{
let _checkBox = new CheckBoxQuestion ({
consultationId: questionsList[key].consultationId,
questionId: questionsList[key].questionId,
questionElementType: questionsList[key].questionElementType[0].title,
questionType: questionsList[key].questionType,
title:questionsList[key].title,
displayId: questionsList[key].displayId,
key: questionsList[key].questionId,
value: questionsList[key].answer.length<=0? null : questionsList[key].answer[0].answerValue.toLowerCase(),
label: questionsList[key].title,
order: 7,
options: questionsList[key].answerOptions.map(function(item){
return {"name": item.ReferenceKey, "key": item.preDefineAnswerOptionId, "value": item.text, "optionSelected": item.preDefineAnswerOptionId==questionsList[key].answer[0].answerValue? "true": "false"}
}),
});
this.mappedQuestions.push(_checkBox);
}
1 回答
如果要取消选中该复选框,则其
[value]
绑定必须是假的 ."true"
和"false"
都是非空字符串,这意味着它们的计算结果为true
.将
"false"
转换为false
,它将按预期工作 .Live demo