我正在使用FormArray和Reactive Forms Module动态生成复选框。
我这里需要做的是,如果用户选中任意2个复选框,我想禁用“休息”复选框。如果他取消选择任何1,则再次允许他从其他人中选择。 完成2个选择后,其余所有功能都将禁用。
下面是HTML PART
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
<label>
<b>Time Out Period :</b>
</label>
<div class="input-group">
<input type="text" class="form-control" maxlength="2" formControlName="tbl_config_TimeoutPeriod">
</div>
<div *ngIf="tbl_config_TimeoutPeriod.invalid && tbl_config_TimeoutPeriod.touched">
<span style="color:red;margin-top:3px">Time Out Period field is mandatory..!</span>
</div>
<br>
<div formArrayName="users">
<div *ngFor="let user of users.controls; index as idx">
<input [formControlName]="idx" type="checkbox" >
<button (click)="deleteUserField(idx)">Delete</button>
</div>
</div>
<br>
<button type="submit" [disabled]="!userForm.valid" class="btn btn-primary">Save Changes</button>
<button type="button" (click)="addUserField()">Add More User</button>
</form>
下面是TS PART
userForm = new FormGroup({
tbl_config_TimeoutPeriod: new FormControl('', Validators.required),
users: new FormArray([
new FormControl('', Validators.required)
])
});
get users(): FormArray { return this.userForm.get('users') as FormArray; }
get tbl_config_TimeoutPeriod() { return this.userForm.get('tbl_config_TimeoutPeriod'); }
onFormSubmit() {
console.log(this.userForm.value); // Gives Complete form data
}
addUserField() {
this.users.push(new FormControl(''));
}
deleteUserField(index: number) {
this.users.removeAt(index);
}
答案 0 :(得分:1)
您可以这样更改输入:
<input type="checkbox"
[disabled]="amountChecked==2&&!input.checked
?'disabled'
:''"
(change)="handleCheck($event.target)"
#input>
...并将其添加到您的component.ts中:
amountChecked=0
handleCheck(ev){
if(ev.target.checked==true){
this.amountChecked++
}else{
this.amountChecked--
}
}
还要更改 deleteUserField()方法:
deleteUserField(index: number,el:HTMLInputElement) {
el.checked=false
this.handleCheck(el)
this.users.removeAt(index);
}
根据要求,我更新了该示例的链接,将问题中的所有代码与我的解决方案合并。此外,我在示例中和上面进行了一些更改,以便能够正确删除输入并正确处理状态。