Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate form Input field as per selected number from dropdown (select)

I want to generate input text boxes as per selected value from dropdown.

<mat-label>Options</mat-label>
<mat-form-field>
 <select matNativeControl name="Options" required>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
 </select>
</mat-form-field>

just after this select box some input fields should be there as per selected number.

like image 234
Abhi Avatar asked Nov 04 '19 11:11

Abhi


3 Answers

I would suggest that you do this with reactive forms. Take a look of this stackblitz here, but it basically boils down to this:

Component UI:

<select matNativeControl name="Options" required (change)="onChange($event.target.value)">
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<div [formGroup]="textBoxFormGroup" *ngFor="let items of items; let i=index">
    <input [formControl]="textBoxFormGroup.controls[i]" type="text" />
</div>

Component Logic:

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


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular';
  items: any[] = [];
  textBoxFormGroup :FormArray

  constructor(public formBuilder:FormBuilder){
    this.textBoxFormGroup = this.formBuilder.array([]);
    this.addControl(0);
    this.addControl(1);
  }
  ngOnInit() {

  }

  onChange(i) {
    while(this.textBoxFormGroup.length > 0) {
      this.items.pop();
      this.textBoxFormGroup.removeAt(0);
    }
    while(i > 0) {
      this.addControl(i);
      i--;
    }
  }

  addControl(i) {
      this.items.push({id: i.toString()})
      this.textBoxFormGroup.push(this.formBuilder.control(''));
  }
}
like image 137
Athanasios Kataras Avatar answered Nov 15 '22 04:11

Athanasios Kataras


The below solution can work for you.

Html code,

      <div>
        <mat-form-field>
          <mat-label> Options</mat-label>
          <mat-select
            [(ngModel)]="selectedValue"
            (selectionChange)="onSelectOption()"
          >
            <mat-option value="2">2</mat-option>
            <mat-option value="3">3</mat-option>
            <mat-option value="4">4</mat-option>
            <mat-option value="5">5</mat-option>
          </mat-select>
        </mat-form-field>
        <div *ngFor="let field of fieldsArray">
          <input type="text" [value]="field" />
        </div>
      </div> 

Component.ts code,

    selectedValue: number = 2;
    fieldsArray: any[] = [];

    onSelectOption() {
        for(let i=1; i<=this.selectedValue; i++) {
            this.fieldsArray.push(i);
        }
    }
like image 27
Gangadhar Gandi Avatar answered Nov 15 '22 04:11

Gangadhar Gandi


You can use FormGroup and FormArray to generate the controls dynamically:

HTML Code:

<mat-form-field>
    <mat-label>Select an option</mat-label>
    <mat-select [(value)]="selected" (selectionChange)="addControlsInFormArray()">
        <mat-option>None</mat-option>
        <mat-option value="1">1</mat-option>
        <mat-option value="2">2</mat-option>
        <mat-option value="3">3</mat-option>
    </mat-select>
</mat-form-field>

    <form [formGroup]="fg" (ngSubmit)="onSubmit()">
        <div formArrayName="inputs" *ngFor="let item of fg.get('inputs').controls; let i = index;">
            <div [formGroupName]="i">
                <mat-form-field class="example-full-width">
                    <input matInput formControlName="question" placeholder="Placeholder text" value="">
  </mat-form-field>
            </div>
        </div>
    </form>

<div style="padding-top:20px">
    <h2>Form Value:</h2>
    {{fg.value | json}}
</div>

TS Code:

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

/** @title Simple form field */
@Component({
  selector: "form-field-overview-example",
  templateUrl: "form-field-overview-example.html",
  styleUrls: ["form-field-overview-example.css"]
})
export class FormFieldOverviewExample {

  fg: FormGroup;
  fa: FormArray;
  selected = 0;

  constructor(private fb: FormBuilder) {
    this.fg = this.fb.group({
      inputs: this.fb.array([])
    });
  }

  addControlsInFormArray() {
    if (this.fa) {
      while (this.fa.length !== 0) {
        this.fa.removeAt(0);
      }
    }
    for (var i = 0; i < this.selected; i++) {
      this.fa = this.fg.get("inputs") as FormArray;
      this.fa.push(this.createItem());
    }
  }

  createItem(): FormGroup {
    return this.fb.group({
      question: new FormControl("")
    });
  }
}

Live Demo

like image 22
Prashant Pimpale Avatar answered Nov 15 '22 04:11

Prashant Pimpale