Angular FormControl 对象能够接受任何类型的输入值,或者仅限于打字稿基元类型



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

我正在使用的系统包括:角度 CLI:7.1.4;节点:10.15.0;角度:7.1.4;RXJS 6.3.3;打字稿 3.1.6;网络包 4.23.1;Linux rdz1 4.15.0-43-generic #46-Ubuntu SMP 星期四 12 月 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))
    }
}

控制台显示如下内容:{注释类型: "信用", 注释日期: "2019-01-01", 注释到: [对象对象], ... }

我正在将一个对象 {param1: val1, parm2: val2} 传递给 "noteTo" ,所以我希望在控制台中观察这个值,但它显示 [对象对象]。看起来对象是否已字符串化。

我已经找到了答案。在表单中,而不是使用:

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

我不得不使用:

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

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

假设对象被"字符串化"是正确的。

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

但是,如果您希望能够从表单转换回来以获取该自定义类型的对象的值,则必须创建一个方法来执行此操作,这可能有点烦人。

另一种解决方案是将自定义类型的属性分解为ndcForm FormGroup内部的嵌套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 文档,了解有关嵌套FormGroup实例的信息。

相关内容

最新更新