0
votes

How to add form fields based on input form user (drop down selection) which can have input, button, check box etc in angular reactive forms.

2
You can use formArray to push dynamically formControls or formGroupsTzimpo

2 Answers

0
votes

You can basically check the value of the selected option from the drop down and display other fields or not based on that using *ngIf

0
votes

I think this is what you are asking for...not using a drop down selection but adding fields dynamically to your form.

see the following example. 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>