【发布时间】:2019-07-19 04:46:48
【问题描述】:
我有一个带有复选框的响应式表单。复选框数组值是从 API 获取的。如果数组属性为“isSelected”,我需要默认设置复选框值:true,(我还需要使用选定值获取该默认值) 谁能帮帮我。
这是我尝试过的。
getData(){
{
this.age= [
{
"ageID": 1,
"description": "0-5 years",
"isSelected": true
},
{
"ageID": 2,
"description": "5-15 years",
"isSelected": true
},
{
"ageID": 3,
"description": "15-35",
"isSelected": false
},
{
"ageID": 4,
"description": "35-60",
"isSelected": false
}
],
this.language= [
{
"languageID": 1,
"description": "Arabic",
"isSelected": false
},
{
"languageID": 2,
"description": "Chinese",
"isSelected": false,
},
{
"languageID": 3,
"description": "Hindi",
"isSelected": false,
},
{
"languageID": 4,
"description": "Tamil",
"isSelected": true,
},
{
"languageID": 5,
"description": "Japanese",
"isSelected": true,
},
]
}
}
onAgeChange(age: any, isChecked: boolean){
const ageFormArray = <FormArray>this.exampleForm.controls.ages;
if (isChecked) {
ageFormArray.push(new FormControl(age));
for(let item in ageFormArray.value){
let obj = {
"ageID": ageFormArray.value[item],
"isSelected": true,
}
console.log(obj)
}
} else {
let index = ageFormArray.controls.findIndex(x => x.value == age)
ageFormArray.removeAt(index);
}
}
onLanguageChange(language: any, isChecked: boolean){
const languageFormArray = <FormArray>this.exampleForm.controls.languages;
if (isChecked) {
languageFormArray.push(new FormControl(language));
for(let item in languageFormArray .value){
let obj = {
"ageID": languageFormArray.value[item],
"isSelected": true,
}
console.log(obj)
}
} else {
let index = languageFormArray.controls.findIndex(x => x.value == language)
languageFormArray.removeAt(index);
}
}
HTML
<div>
<h1>Reactive form</h1>
<div class="custom-control custom-checkbox" *ngFor="let data of age let j = index">
<input type="checkbox" (change)="onAgeChange( data.ageID ,$event.target.checked,$event)" name="age"> {{data.description}}<br>
</div>
<br>
<div class="custom-control custom-checkbox">
<div class="custom-control custom-checkbox" *ngFor="let data of language">
<input type="checkbox" (change)="onLanguageChange(data.description, $event.target.checked)"> {{data.description}}<br>
</div>
</div>
</div>
【问题讨论】:
-
你能解释一下为什么你没有在复选框上使用
formControlName指令吗?
标签: angular angular-reactive-forms