我是角度6的新手,我需要标记复选框。
我有两个数组:
this.skillArray = [
{ID: 1, name: "الغطس"},
{ID: 2, name: "الحريق"},
{ID: 3, name: "المعالجة"},
{ID: 4, name: "الميكانيكا"},
{ID: 5, name: "السيول"},
{ID: 6, name: "التغريز"},
{ID: 7, name: "الكهرباء"},
{ID: 8, name: "الاحتفالات"},
{ID: 9, name: "المناسبات"},
{ID: 10, name: "الصلاة"}
]
var splitstr = ["9", "7"];
然后我们要检查9和7 id的复选框已选中。我尝试解决它,然后成功标记这些复选框,但我也在复选框中添加了一个onchenge函数来发布该值。所以问题是那些复选框被检查的值没有被推送到数组。那么如何解决它。
<form [formGroup]="myForm">
<div *ngFor="let data of skillsArray">
<p><input type="checkbox" [checked]="inputChecked(data.ID)" (change)="onChange(data.ID, $event.target.checked)"> {{data.name}}</p>
</div>
</form>
inputChecked(id:any) {
let checked = false;
console.log(this.splitstr);
for (let l = 0; l <this.splitstr.length; l++) {
let temp = this.splitstr[l];
if (temp == id) {
checked = true;
}
}
return checked;
}
onChange(value: any, isChecked: boolean) {
const skillFormArray = <FormArray>this.myForm.controls.VFields;
if (isChecked) {
skillFormArray.push(new FormControl(value));
}
else
{
let index = skillFormArray.controls.findIndex(x => x.value == value)
skillFormArray.removeAt(index);
}
}
答案 0 :(得分:0)
您应该这样尝试:
您的组件代码:
activeEls = [];
neededValues = [1,3];
changeStatus(car: Cars){
car.checked = !car.checked;
if(car.checked){
this.activeEls.filter(function(value, index, arr){
return value == car.id;
});
}
else{
this.activeEls.splice(this.activeEls.indexOf(car.id),1);
}
console.log(car.id, " status= ", car.checked);
}
ifOneAndThreeIsActive(){
for (let ca of this.cars){
if(this.activeEls.includes(ca.id))
continue;
if(ca.checked)
this.activeEls.push(ca.id);
}
let concur = 0;
for(let j = 0, l1 = this.activeEls.length; j < l1; j++){
if(this.neededValues.length <= j && !this.activeEls.includes(this.neededValues[j])){
continue;
}
++concur;
if(concur == this.neededValues.length && this.activeEls.length === this.neededValues.length)
console.log(this.neededValues, 'correct');
console.log(concur);
}
console.log(this.activeEls);
}
您的HTML文件:
<ul class="list-group">
<li class="list-group-item" *ngFor="let car of cars">
<input type="checkbox" (click)="changeStatus(car)" [checked]="car.checked">
</li>
</ul>
<button class="btn btn-info" (click)="ifOneAndThreeIsActive()">Check if 1 & 3 are active</button>
推
或这样,如果在我的示例中仅选择1&3时才需要此功能,则应更改为数字。
此解决方案套件适合您吗?