Home > Net >  Angular Reactive Forms map only part of object to formControlName
Angular Reactive Forms map only part of object to formControlName

Time:01-06

I have a select input that chooses from a list of objects, displays a name, and also binds it into a form's field. However, I need that whole object available for the change event. Changing formControlName is not really an option.

HTML:

<form [formGroup]="form">
  <!-- Here I can access $event.target.value to obtain just the userName -->
  <select formControlName="userName" (change)="process($event.target.value)">
    <option [value]="user.name" *ngFor="let user of users">{{ user.name }}</option>
  </select>

  <!-- I would like to have access to the entire object -->
  <!-- <select formControlName="userName" (change)="processUser(user)" -->
  <!--   <option *ngFor="let user of users">{{ user.name }}</option> -->
  <!-- </select> -->
</form>

<span>The value is: {{ form.get('userName').value }}</span>

TS:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  form: FormGroup;

  users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Mary' },
    { id: 3, name: 'Michael' }
  ]

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({ userName: [null] });
  }

  process(userName) {
    console.log(userName);
  }

  // Here I need the entire user object
  processUser(user) {
    // do stuff
  }

  // I can always do this (in my case names are guaranteed to be unique)
  // but it's a really ugly workaround
  processUserWorkaround(userName) {
    const user = this.users.find(u => u.name == userName);
    //do stuff
  }
}

Full Stackblitz

CodePudding user response:

You can access the selected index on the change event with $event.target.selectedIndex. You can use this index to get the whole object from the users array and passed that object to processUser method.

Example

<select
  formControlName="userName"
  (change)="processUser(users[$event.target.selectedIndex])"
>
  <option *ngFor="let user of users" [value]="user.name">{{ user.name }}</option>
</select>

Stackblitz

https://stackblitz.com/edit/angular-7kjrps

  •  Tags:  
  • Related