Search code examples
angularbindingangular-reactive-forms

How To Bind Select Option to Input Field


I'm trying to get a value from a select option to bind to an input field and that value populates my form property in my reactive form. Here is my code:

import 'zone.js/dist/zone';
import { Component, ElementRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import {
  FormArray,
  FormBuilder,
  FormControl,
  FormGroup,
  FormsModule,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
  templateUrl: 'main.html',
})
export class App {
  name = 'Angular';
  
  @ViewChild('templates') templates !: ElementRef
  optionChoice: any = '';
  taxonomyResponse: any = {
    categoryList: [
      {
        name: 'Option 1',
      },
      {
        name: 'Option 2',
      },
      {
        name: 'Option 3',
      },
    ],
  };

  form!: FormGroup;

  constructor(private fb: FormBuilder) {}
  selectForm = this.fb.group({
    selectOption: ''
  })

  onChange() {
    this.optionChoice = this.templates.nativeElement.value;
    console.log(this.optionChoice)
  }

  submit() {
    console.log(this.selectForm.value);
  }

}


bootstrapApplication(App);

Here is my HTML

<form [formGroup]="selectForm" (ngSubmit)="submit()">
  <select id="dropdown" class="form-select" #templates (change)="onChange()">
    <option>Please Select Option</option>
    <option *ngFor="let t of taxonomyResponse.categoryList">{{t.name}}</option>
  </select>
  <input type="text" formControlName="selectOption" value="{{optionChoice}}" />
  <button type="submit" id="submit">Submit</button>
</form>

I want to be able to take the value from the selected option, bind it to the input field and display the value on my form property. I know that I am missing one part, I just can't figure it out.

Here is a link to Stack Blitz

Thank you


Solution

  • You shouldn't use the value attribute in this case.

    <input type="text" formControlName="selectOptions" />
    

    Instead, you should iterate each FormGroup in the options FormArray and set the value to the selectOption FormControl via patchValue method.

    onChange() {
      this.optionChoice = this.templates.nativeElement.value;
      console.log(this.optionChoice);
    
      for (let i = 0; i < this.options.length; i++) {
        (this.options.controls[i] as FormGroup).controls.selectOptions.patchValue(
          this.optionChoice,
          { emitEvent: false }
        );
      }
    }
    

    Demo @ StackBlitz