Angular FormControl对象能够接受任何类型的输入值,还是限于打字稿原语类型?

时间:2019-01-04 14:29:07

标签: angular typescript angular-reactive-forms

我正在使用FormGroup中的FormControl对象在Angular中创建反应形式。当我将原始参数作为HTML输入选择控件的值传递时,没有问题。但是,当我传递自定义类的对象时,FormControl中的值将减少为[object Object]。

我正在使用的系统包括: 角CLI:7.1.4; 节点:10.15.0; 角度:7.1.4; rxjs 6.3.3; 打字稿3.1.6; webpack 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]。看起来好像该对象已被字符串化。

2 个答案:

答案 0 :(得分:2)

我找到了答案。在表单中,不要使用:

<option *ngFor="let cargoAg of dfCargoAgs" [value]="cargoAg">{{cargoAg.nombre}}</option>

我必须使用:

<option *ngFor="let cargoAg of dfCargoAgs" [ngValue]="cargoAg">{{cargoAg.nombre}}</option>

因此[value]仅接受基本类型,但是[ngValue]可以接受任何类的对象。 我希望这会有所帮助。

答案 1 :(得分:0)

您以为对象已“字符串化”是正确的。

您可以在自定义类型上覆盖toString(),以便以HTML格式获取所需的输出。

但是,如果您希望能够从表单转换回以获取该值作为该自定义类型的对象,则必须创建一个这样做的方法,这可能会很烦人。

另一种解决方案是将自定义类型的属性分解为FormGroup ndcForm内部的嵌套FormGroup,如下所示:

ndcForm: FormGroup = new FormGroup({
    noteType: new FormControl(''),
    noteDate: new FormControl(''),
    noteFor: new FormControl(''),
    noteTo: new FormGroup({
        any: new FormControl(''),
        custom: new FormControl(''),
        property: new FormControl('')
    }),
    noteDetail: new FormControl(''),
    noteDetailVal: new FormControl(''),
    noteChkRefInvoice: new FormControl('')
});

您将必须小心从对象中提取每个值,然后将其放入表单中,反之亦然。

转到Angular文档以获取有关nesting FormGroup instances的信息。