簡體   English   中英

如何在formGroup內部的formGroupName之間切換內容

[英]How to switch content between formGroupName inside formGroup

我的formGroup中有兩個單選按鈕,可以說選項1,選項2。 在formGroup里面,假設它是Parent,我有formGroupName可以說它是孩子。 根據單選按鈕的選擇,即選項1和選項2,我需要更改子內容。

`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>`

使用addControl()方法可動態添加控件以形成組。

Component.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM