我有一个表单,还有一个复选框和一个文本框。如果未选中复选框,则Textbox是强制性的。所以我写了下面的代码,它运行得很好。
autoCodeCheckbox: FormControl = new FormControl();
autoCodeInput: FormControl = new FormControl('', Validators.required);
ngOnInit(): void {
this.frmExpenseHead = new FormGroup({
autoCode: this.autoCodeCheckbox,
code: this.autoCodeInput
});
this.autoCodeCheckbox.valueChanges.subscribe(data => {
if (data) {
this.autoCodeInput.setValidators(null);
}
else {
this.autoCodeInput.setValidators(Validators.required);
}
this.autoCodeInput.updateValueAndValidity();
});
}现在我有了另一种形式。有一组复选框和一个文本框。基于textbox值,我想要复选框强制。现在,我不知道如何像上面的代码那样声明复选框组。
userName: FormControl = new FormControl('');
checkArray: .......
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.form = this.fb.group({
userNameInput: userName,
checkArray: this.fb.array([], [Validators.required])
})
} 发布于 2021-06-06 06:42:27
一个简单的解决方案创建了一个可重用的组件(哑巴),它提供了所需的功能。在这里,您可以创建一个具有textbox和复选框的组件,我们可以通过输入提供名称或任何其他动态数据。
然后,通过循环遍历主组件,可以轻松地使用该组件来呈现多个复选框和文本输入。
简单示例->
在主要组成部分中
constructor(private fb: FormBuilder) {
this.myFormGroup = this.fb.group({});
}
ngOnInit() {
//dynamic formcontroller name create by appending index
[array of those component].map((data, i) => {
this.myFormGroup.addControl('mySet'+i, this.fb.control(data.propertUNeed))
})
}和内部模板
<div *ngFor="let ctrl of myFormGroup.controls | keyvalue">
..... do what ever thing u need
</div>发布于 2021-06-06 08:26:15
您还可以使用FormArray和FormGroup实现。
你的Component.ts文件
export class HomeComponent implements OnInit {
formArray: FormArray;
formGroups: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.formGroups = this.fb.group({
name: '',
check: this.fb.array([])
});
this.addGroup(true, 'John');
this.addGroup(true, 'David');
this.addGroup(true, 'Francis');
this.formGroups.valueChanges.subscribe(() => {
console.log(this.getGroupArray.controls);
});
}
createGroup(checkText: boolean, name: string = '') {
return new FormGroup({
checkbox: new FormControl(checkText),
name: new FormControl(name)
});
}
addGroup(checkbox: boolean, name: string) {
this.getGroupArray.push(this.createGroup(checkbox, name));
}
get getGroupArray(): FormArray {
return this.formGroups.get('check') as FormArray;
}
}你的component.html文件
<form [formGroup]="formGroups">
<div formArrayName="check">
<div *ngFor="let check of getGroupArray.controls; let i= index">
<div [formGroupName]="i">
<input type="checkbox" formControlName="checkbox">
<input type="text" formControlName="name">
</div>
</div>
</div>
</form>https://stackoverflow.com/questions/67856326
复制相似问题