用户输入角度6的动态反应形式

时间:2020-03-21 21:29:14

标签: angular angular-reactive-forms

如何根据输入表单用户(下拉选择)添加表单域,该表单域可以在角反应形式中包含输入,按钮,复选框等。

2 个答案:

答案 0 :(得分:0)

您基本上可以使用* ngIf

从下拉列表中检查所选选项的值,并显示其他字段或不基于该字段。

答案 1 :(得分:0)

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

请参见以下示例。 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>