我想动态地向 Angular 反应形式添加输入控件。为此,如果用户从下拉列表中选择文本框输入控件,则文本框的某些特定属性字段应显示为 i.e。占位符和其他控件的情况相同。为此,我将输入控件信息存储在一个数组中。但是我不知道在选择特定控件时如何显示存储在数组中的控件相关属性。组件类代码如下所示:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {  
  reviewForm: FormGroup;

  controlArray = [
    {
      name:'text', 
      attributes: {placeHolder: 'Placeholder', type:'text'},            
    },
    {
      name:'radio', 
      attributes:[ 
        {radioTitle: 'radioButton'}
      ]
    },
    {
      name:'checkbox', 
      attributes: {checkTitle: 'checkBox'}
    },
    {
      name:'select', 
      attributes: {option: 'optionNo.'}
    },
    {
      name:'textarea', 
      attributes: {}
    },
    {
      name:'button', 
      attributes: {}
    }
  ];
  selectedControl: any;   
  isClicked:boolean= false;
  label: string;
  isRequired:boolean = false;
  placeHolderValue: string = "";
  ngOnInit(){
    this.reviewForm = new FormGroup({   
      // 'placeHolder' : new FormControl(null),   
      'controlArray': new FormArray([

    ])
    });
  }

  addControl(){    
      this.isClicked = true;
      const control = new FormControl(this.selectedControl);
      (<FormArray>this.reviewForm.get('controlArray')).push(control);      
      // console.log(this.selectedControl);      
    }  

  onSubmit(){
    console.log(this.reviewForm);
  }
}

组件模板代码是这样的:

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <div class="form-group">
        <label for="input">Select Input: </label>
        <select [(ngModel)]="selectedControl" class="form-control">
          <option *ngFor="let control of controlArray; let i=index" 
            [value]="control">{{controlArray[i].name}}</option>                                              
        </select> 

        <!-- Common Fields -->
        <label for='name'>Label: </label>
        <input id="name" type="text" [(ngModel)]="label" >
<label for='required'>Required: </label> <input type="checkbox" [(ngModel)]="isRequired" >
</div> <form [formGroup]="reviewForm" > <span *ngIf="isClicked"> <div formArrayName="controlArray"> <div class="form-group" *ngFor="let control of reviewForm.get('controlArray').controls; let i = index"> <label>{{label}} </label> <input type="{{control.value}}" class="form-control" [formControlName]="i" > </div> </div> </span> <button type="button" (click)="addControl()">Add</button> <!-- <button type="button" (click)="clicked()">Add</button>
--> <!-- <button class="btn btn-primary" type="submit">Submit</button> --> </form> </div> </div> </div>