如何有条件地生成angular 6个动态反应形式

How to generate angular 6 dynamic reactive form conditionally

我有 angular 动态反应形式,我想根据条件显示更多字段。例如:基于下拉选择,我想在表单中显示一个动态字段。

  <form *ngIf="formGroup" [formGroup]="formGroup" class="form">
  <div  fxLayout="column" *ngFor="let field of fields;let i=index;" 
         [ngSwitch]="field.type">
   <mat-form-field *ngSwitchCase="'text'">
      <input matInput [placeholder]="field.label" 
  [formControlName]="field.name" [id]="field.name">
      <mat-error>{{field.error}}</mat-error>
    </mat-form-field>

 <mat-form-field *ngSwitchCase="'dropdown'">
  <mat-select placeholder="{{field.label}}" [formControlName]="field.name" 
(selectionChange)="onDropDownChange($event)">
    <mat-option  *ngFor="let item of field.items" [value]="item">
      {{item.fact}}
    </mat-option>
  </mat-select>
  </mat-form-field>
 <button (click)="add(formGroup)">
    ADD
  </button>    

dynamicform.component.ts

 export class dynamicFormComponent implements OnInit {
  formGroup: FormGroup;
   fields;
  ngOnInit() {
 this.formGroup = this.createFormControls();
  this.fields = [{
 {
    name:"categoryname",
    error:"Please Select ",
    label:"Category",
    type: "text", 
    validation: Validators.required

 },{  name:"categoryType",
    error:"Please Select ",
    label:"Category Type",
    type: "dropdown", 
    items: ['cat1','cat2'],
    validation: Validators.required
  }]
 }
 onDropDownChange(event){
   if(event.value  === 'cat1') {
   // logic to add sub category to form
  }
 createControlForm() {
 let fm = {};
 this.fields.forEach((f) => {
 fm[f.name] = new FormControl('', 
  this.validators(f.validation));
 });
 }
  }

我可以生成包含类别名称和类别类型的表单。现在我需要根据下拉选择生成一个字段子类别

Angular form API 提供名为 disable 属性 的功能,它将从表单中排除 formcontrol,我们可以手动启用 formcontrol

component.ts

this.form = this.fb.group({
     cName:'',
     cType:'',
     extraOption:{disabled: true, value:""}
   })

this.cType.valueChanges.subscribe((v)=>{
     if(v == 'cat1'){
       this.extraOption = true;
      //Enabling the formControl Using formControl enable() method
       this.form.get('extraOption').enable();
     }
   })

示例:https://stackblitz.com/edit/angular-ybhrhd