【问题标题】:Dynamic reactive forms with user input in angular 6具有角度 6 的用户输入的动态反应形式
【发布时间】:2020-03-22 06:56:41
【问题描述】:

如何根据输入表单用户(下拉选择)添加表单字段,该用户可以在角度反应表单中具有输入、按钮、复选框等。

【问题讨论】:

  • 可以使用formArray动态推送formControls或formGroups
  • @Tzimpo 你有这种情况的工作例子吗?

标签: angular angular-reactive-forms


【解决方案1】:

您基本上可以从下拉列表中检查所选选项的值,并根据使用 *ngIf 显示其他字段或不显示其他字段

【讨论】:

    【解决方案2】:

    我认为这就是您所要求的...不使用下拉选择,而是将字段动态添加到您的表单中。

    请参阅以下示例。 https://angular-vfeusd.stackblitz.io

    app.component.ts

    import { Component } from '@angular/core';
    import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
      form: FormGroup;
      newFieldName: string;
      controlNames: string[] = [];
      pageMessage = "";
    
      constructor(private fb:FormBuilder){
        this.form = fb.group({})
      }
    
      addToForm(event){
        console.log(this.newFieldName);
        const ctrl = new FormControl();
        ctrl.validator = Validators.required;
        ctrl.setValue(null);
        this.form.addControl(this.newFieldName, ctrl)
        this.controlNames.push(this.newFieldName);
        this.newFieldName = '';
      }
      submitForm(){
        if(!this.form.valid){
              this.pageMessage = "invalid form"
        }    
        this.pageMessage = '';
        console.log(this.form.value)
      }
    }
    
    
    app.component.ts
    <hello name="{{ name }}"></hello>
    <p>
      Start editing to see some magic happen :)
    </p>
    
    Enter input name:  
    <input type="text" name="formfieldname" [(ngModel)]="newFieldName">
    <button type="button" name="enterButton" (click)="addToForm($event)">Enter</button>
    <hr>
    {{pageMessage}}
    <form [formGroup]="form">
      <table>
      <tr *ngFor="let c of controlNames; let x=index">
    
        <td>{{c}}</td>
        <td><input type="text" name="{{c}}" 
            value="" placeholder="enter value" [formControlName]="c">   
            </td>
      </tr>
      </table>
      <button type="button" name="formsubmit" (click)="submitForm()">Submit Form</button>
    </form>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-23
      • 2019-05-24
      • 2019-02-23
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多