如何使用角度7反应形式访问下拉选择的项目属性

时间:2019-06-18 06:09:17

标签: angular angular7 angular-reactive-forms angular8

在下面的示例中,我有一个简单的下拉列表,其中包含客户列表。从下拉列表中选择客户时,我需要执行以下操作。

  1. 所选客户名称应显示在 "txtCustomerName" 文本框中。
  2. 选定的客户名称应显示在 "spnCustomerId" 跨度元素中(我已经以某种方式做到了这一点,并且我想确定自己是否以正确的方式在反应形式)。

除上述内容外,页面加载时出现"ERROR TypeError: control.registerOnChange is not a function"错误。我发现了以下关于stackoverflow的类似文章,但是找不到我所面临问题的可靠答案。

ERROR TypeError: control.registerOnChange is not a function

ERROR TypeError: control.registerOnChange is not a function --> formControlName

我的组件类如下

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  public myForm: FormGroup;
  public allCustomers: Customer[] = new Array();

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.myForm = this.formBuilder.group({
      selectedCustomer: this.formBuilder.group({
        id: [],
        name:['']
      })
    })

    this.allCustomers.push(new Customer(0, "John"));
    this.allCustomers.push(new Customer(1, "Kumar"));
    this.allCustomers.push(new Customer(2, "Warma"));
    this.allCustomers.push(new Customer(3, "Sabitha"));
  }

  changeCustomer(e) {
    console.log(JSON.stringify(this.myForm.get('selectedCustomer').value));
  }
}

export class Customer {
  public id: number;
  public name: string;

  constructor(cusId: number, cusName: string) {
    this.id = cusId;
    this.name = cusName;
  }
}

我的html页面如下

<form name="frmMain" [formGroup]="myForm">
  <div>
    <div>
      All customers:
      <select (change)="changeCustomer($event)" formControlName="selectedCustomer">
        <option value="" disabled>Please select</option>
        <option *ngFor="let cus of allCustomers" [ngValue]="cus">{{cus.name}}</option>
      </select>
    </div>
    <br/>
    <div>
      Selected customer id :
      <span id="spnCustomerId">{{myForm.get('selectedCustomer').value.id}}</span>
    </div>
    <div>
      Selected customer name :
      <!-- I need to show selected customer name in below text box -->
      <input id="txtCustomerName" type="text"/>
    </div>
  </div>
</form>

请参见上方stackblitz

中的示例

3 个答案:

答案 0 :(得分:1)

尝试这样:

TS:

this.myForm = this.formBuilder.group({
  selectedCustomer: [],
  selectedCustomerName : []
})


changeCustomer(e) {
    console.log(JSON.stringify(this.myForm.get('selectedCustomer').value));
    let name = (this.myForm.get('selectedCustomer').value).name

    this.myForm.patchValue({
      selectedCustomerName : name
    });
  }

模板:

<div>
  Selected customer id :
  <span id="spnCustomerId">{{myForm.get('selectedCustomer').value?.id}}</span>
</div>
<input id="txtCustomerName" type="text" formControlName="selectedCustomerName"/>

答案 1 :(得分:1)

发生错误,是因为您正在使用FormBuilder初始化表单,但是模板中并不存在所有控件(请参见此处link)。

尝试一下:

this.myForm = this.formBuilder.group({
  selectedCustomer: [''],
  name: ['']
})

除了添加更改侦听器外,您还可以直接订阅formControl,如下所示:

this.myForm.get('selectedCustomer').valueChanges
  .subscribe(e => {
    this.myForm.get('name').setValue(e.name);
    })

在模板中:

<input id="txtCustomerName" type="text" formControlName="name"/>

答案 2 :(得分:1)

对不起,答案不正确。参见forked stackblitz

您对Angular说selectedCustomer是一个FormGroup

selectedCustomer: this.formBuilder.group({
        id: [],
        name:['']
      })

但是您试图在使用select时为FormGroup提供一个值作为对象

<select (change)="changeCustomer($event)" formControlName="selectedCustomer">
        <option value="" disabled>Please select</option>
        <option *ngFor="let cus of allCustomers" 
             [ngValue]="cus">{{cus.name}}</option>
</select>

这是因为您有错误。

解决方案是selectedCustomer是对象,而不是FormGroup,是的,FormControl可以存储对象,而不仅仅是字符串或数字

this.myForm = this.formBuilder.group({
      selectedCustomer: []
    }) 

当然,在使用安全运算符显示“名称”和“ id”时要小心,因为可以为空

<span id="spnCustomerId">{{myForm.get('selectedCustomer').value?.id}}</span>