Search code examples
htmlangularangular7

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.


Solution

  • 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(''));
      }
    }