【问题标题】:Angular Reactive Forms map only part of object to formControlNameAngular Reactive Forms 仅将对象的一部分映射到 formControlName
【发布时间】:2022-01-04 23:10:36
【问题描述】:

我有一个选择输入,它从对象列表中进行选择,显示名称,并将其绑定到表单的字段中。但是,我需要整个对象可用于change 事件。更改formControlName 并不是一个真正的选择。

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

【问题讨论】:

标签: angular angular-reactive-forms reactive-forms


【解决方案1】:

您可以使用$event.target.selectedIndex 访问更改事件中的选定索引。您可以使用此索引从users 数组中获取整个对象,并将该对象传递给processUser 方法。

示例

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

堆栈闪电战

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2020-07-16
    • 2023-04-11
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多