Html 如何在formGroup内部的formGroupName之间切换内容
我的表单组中有两个单选按钮,比如选项1,选项2。在formGroup内部,假设它是父级,我有formGroupName,假设它是子级。根据单选按钮的选择,即选项1和选项2,我需要更改子内容Html 如何在formGroup内部的formGroupName之间切换内容,html,angular,typescript,Html,Angular,Typescript,我的表单组中有两个单选按钮,比如选项1,选项2。在formGroup内部,假设它是父级,我有formGroupName,假设它是子级。根据单选按钮的选择,即选项1和选项2,我需要更改子内容 `MyForm : FormGroup; initMyForm(){ this.MyForm = this.fb.group({ id= [''], key=[''], details= this.detailsone,//here I need to put detailone or
`MyForm : FormGroup;
initMyForm(){
this.MyForm = this.fb.group({
id= [''],
key=[''],
details= this.detailsone,//here I need to put detailone or
//detailstwo based on selected radio button
//(keyType)
})
}
get detailsone(){
return this.fb.group({
firstname:[''],
lastname:['']
});
}
get detailstwo(){
return this.fb.group({
college:[''],
subject:['']
});
}
<form [formGroup]="MyForm">
<mat-radio-group formControlName='keyType'>
<mat-radio-button value="option-1" >option-1</mat-radio-button>
<mat-radio-button value="option-2" >option-2</mat-radio-button>
</mat-radio-group>
<div formGroupName="details">
<div *ngIf="option-1">
<input type='text' formControlName='firstname'>
<input type='text' formControlName='lastname'>
</div>
<div *ngIf="option-2">
<input type='text' formControlName='college'>
<input type='text' formControlName='subject'>
</div>
</div>
</form>`
`MyForm:FormGroup;
initMyForm(){
this.MyForm=this.fb.group({
id=[''],
键=[''],
details=this.detailsone,//这里我需要放置detailone或
//基于所选单选按钮的详细信息
//(按键式)
})
}
获取详细信息{
返回此.fb.group({
名字:[''],
姓氏:['']
});
}
获取详细信息wo(){
返回此.fb.group({
学院:[''],
主题:['']
});
}
备选方案1
备选方案2
`
使用addControl()方法将控件动态添加到表单组中
组件。ts
MyForm: FormGroup
constructor(private fb: FormBuilder) {
this.initMyForm();
this.keyType.valueChanges.subscribe((value) => {
if (value === 'option1') {
this.MyForm.removeControl('details');
this.MyForm.addControl('details', this.detailsOne());
} if (value === 'option2') {
this.MyForm.removeControl('details');
this.MyForm.addControl('details', this.detailstwo());
}
});
}
component.html
<form [formGroup]="MyForm">
<mat-radio-group aria-label="Select an option" formControlName="keyType">
<mat-radio-button value="option1">Option 1</mat-radio-button>
<mat-radio-button value="option2">Option 2</mat-radio-button>
</mat-radio-group>
<div *ngIf="MyForm.get('details')" formGroupName="details">
<div *ngIf="MyForm.get('keyType').value === 'option1'">
<input type='text' formControlName='firstname'>
<input type='text' formControlName='lastname'>
</div>
<div *ngIf="MyForm.get('keyType').value === 'option2'">
<input type='text' formControlName='college'>
<input type='text' formControlName='subject'>
</div>
</div>
</form>
选择1
选择2
为什么不创建一个包含名字、姓氏、学院和科目的唯一表单组“详细信息”?注意:“if”必须是*ngIf=“MyForm.get('keyType')。value=='option-1'