首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在formGroupName内部formGroup中切换内容

如何在formGroupName内部formGroup中切换内容
EN

Stack Overflow用户
提问于 2019-08-27 03:41:38
回答 1查看 450关注 0票数 0

我的formGroup中有两个单选按钮,让我说选项-1,选项-2。在formGroup里面,让我们说它是父母,我让formGroupName说它是孩子。根据选择的单选按钮,即选项-1和选项-2,我需要改变子内容。

代码语言:javascript
复制
`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>`
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-27 05:09:30

使用addControl()方法动态添加控件以形成组。

Component.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
<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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57667401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档