angular - 如何使用 Angular 7 反应形式访问下拉选定项目属性
问题描述
在以下示例中,我有一个简单的下拉列表,其中包含客户列表。当您从下拉列表中选择客户时,我需要完成以下操作。
- 选定的客户名称应显示在
"txtCustomerName"
文本框中。 - 选定的客户名称应显示在
"spnCustomerId"
span 元素中(我已经以某种方式完成了它,我想确保我是否使用Reactive Forms以正确的方式进行操作)。
除了上述之外,"ERROR TypeError: control.registerOnChange is not a function"
加载页面时出现错误。我在 stackoverflow 上发现了类似的帖子,但我找不到我面临的问题的可靠答案。
错误类型错误:control.registerOnChange 不是函数
错误类型错误:control.registerOnChange 不是函数 --> 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>
解决方案
试试这样:
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"/>
推荐阅读
- c# - 用户数据未显示在模态中,但在单击按钮时会打开新选项卡,但第一条记录除外
- java - TokenEnhancer 不仅向 jwt 添加了附加信息,还向响应对象添加了附加信息
- google-cloud-platform - 通过 jenkins 推送 docker 镜像
- django - “WSGIRequest”对象没有属性“thema”
- r - 使用字符串作为参数的替换在 R 中编辑函数
- azure - jenkins 作业无法读取服务结构注册表项
- javascript - 在表格单元格内添加段落
- php - 解析时间格式
- ios - 呈现景观控制器崩溃 SplitViewController
- python - ModuleNotFoundError:没有名为“src”的模块