通过添加新控件替换HTML输入控件

时间:2017-10-23 07:28:32

标签: angular angular-reactive-forms ngif formarray

我正在处理Angular反应表单,我想动态地向Angular表单数组添加控件。但是当我添加一个选择框或文本区域时,之前添加的控件也会被新添加的控件替换。我认为HTML代码中存在一些问题:

<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>   
              <!-- {{selectedControl.attributes.value}}              -->
              <span *ngIf="!(selectbox || textarea);else dropdown">
                <input 
                  type="{{control.value}}"                                      
                  class="form-control"     
                  placeholder="abc"                                                  
                  [formControlName]="i"
                  >
              </span>
              <ng-template #dropdown>
                <span *ngIf="selectbox;else comment">
                  <select
                    class="form-control"
                    [formControlName]="i">
                    </select>                                     
                </span>  
                <ng-template #comment>
                  <span *ngIf="textarea">
                    <textarea name="Comment" id="" cols="30" rows="10"></textarea>  
                  </span> 
                </ng-template>  
              </ng-template>                                             
            </div>  
          </div>  
        </span>
        <button type="button" (click)="addControl()">Add</button>  
        <!-- <button type="button" (click)="clicked()">Add</button><br />                 -->
        <!-- <button class="btn btn-primary" type="submit">Submit</button> -->
      </form>

这是组件类代码:

addControl(){    
      this.isClicked = true;
      const control = new FormControl(this.selectedControl.name, Validators.required);
      (<FormArray>this.reviewForm.get('controlArray')).push(control);      
      switch(this.selectedControl.name){
        case 'select':
          this.selectbox = true;
          break;
        case 'textarea':
          this.textarea = true;
          break;
        default:
          break;
      }
      // console.log(this.selectedControl);            
    }

是我项目的stackblitz演示网址: https://stackblitz.com/edit/angular-mjiu8x

请帮忙。

0 个答案:

没有答案