Angular FormControl 对象能够接受任何类型的输入值,还是仅限于 typescript 原始类型?

标签 angular typescript angular-reactive-forms

我在 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/

相关文章:

angular - 如何使 Stencil & Angular Universal 工作

javascript/typescript 对象空检查

Angular 6 嵌套响应式(Reactive)表单组件

angular - 获取错误 : formGroup expects a FormGroup instance. 请传入一个

angular - 我如何让 Angular 5 等待 Injectable 的构造函数中使用的 Promise 在构造依赖项或 ngOnInit 之前解析?

typescript - 类型 'Key' 不能用于索引类型 'Object'

javascript - 类型 '' 上不存在属性 'Request<ParamsDictionary>'

angular - 必须在索引 : 1 - Error 处为表单控件提供一个值

Angular react 形式 : how to pre load form inputs with information

angular - angular http请求同时发送两次