我在 FormGroup 中使用 FormControl 对象在 Angular 中创建响应式(Reactive)表单。当我将原始参数作为 HTML 输入选择控件的值传递时没有问题。但是,当我传递一个自定义类的对象时,FormControl 中的值被缩减为[object Object]。
我正在使用的系统包括: Angular CLI:7.1.4; 节点:10.15.0; Angular :7.1.4; RXJS 6.3.3; typescript 3.1.6; 网络包 4.23.1; Linux rdz1 4.15.0-43-generic#46-Ubuntu SMP Thu Dec 6 14:45:28 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-header-notes',
templateUrl: './header-notes.component.html',
styleUrls: ['./header-notes.component.css']
})
export class HeaderNotesComponent implements OnInit {
ndcForm = new FormGroup({
noteType: new FormControl(''),
noteDate: new FormControl(''),
noteFor: new FormControl(''),
noteTo: new FormControl(''),
noteDetail: new FormControl(''),
noteDetailVal: new FormControl(''),
noteChkRefInvoice: new FormControl('')
});
ngOnInit() { this.onChanges(); }
onChanges(): void{
this.ndcForm.valueChanges
.subscribe( val => console.log(val))
}
}
控制台显示如下: {noteType: "credit", noteDate: "2019-01-01", noteTo: [object Object], ... }
我正在将一个对象 {param1: val1, parm2: val2} 传递给 "noteTo",所以我希望在控制台中看到这个值,但是它显示的是 [object Object]。看起来对象是否已被字符串化。
最佳答案
我找到了答案。在表单中,而不是使用:
<option *ngFor="let cargoAg of dfCargoAgs" [value]="cargoAg">{{cargoAg.nombre}}</option>
我必须使用:
<option *ngFor="let cargoAg of dfCargoAgs" [ngValue]="cargoAg">{{cargoAg.nombre}}</option>
所以 [value] 只接受基本类型,但是 [ngValue] 可以接受任何类的对象。 我希望这会有所帮助。
关于Angular FormControl 对象能够接受任何类型的输入值,还是仅限于 typescript 原始类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54040866/