【问题标题】:(Angular 5) Error: Cannot read property 'setValue' of undefined(Angular 5)错误:无法读取未定义的属性“setValue”
【发布时间】:2019-02-26 07:45:04
【问题描述】:

我正在以这种方式初始化我的表单,但是当我需要编辑它时,它不接受值

组件.ts

ngOnInit() {
  this.tinvoiceService.initForm();
}

tinvoice.service.ts

form: FormGroup;

constructor(
  private _fb: FormBuilder, 
  private invoiceService: InvoiceService
) {}

initForm(): void {
  this.form = this._fb.group({
    customer: [null, Validators.required],
    totalPrice: 0,
    purchases: this._fb.array([])
  });

  // initialize stream
  const myFormValueChanges$ = this.form.controls['purchases'].valueChanges;
  myFormValueChanges$.subscribe(purchases => this.updatePurchasesAmount(purchases));

}

我通过 HTML 传递值

tinvoice.component.html

<a 
  class="btn btn-outline-info text-info" 
  (click)="tinvoiceService.populateForm(invoice)">
  Edit
</a>

tinvoice-list.component.ts

populateForm(invoice) {
  this.form.setValue(invoice);  
}

通过控制台我得到了这个结果

View in StackBlitz

有什么想法吗?

【问题讨论】:

  • 你在哪里打电话initForm()?
  • 另一个组件 ngOnInit() {this.tinvoiceService.initForm();}
  • 您确定在第一次调用 form.setValue() 之前调用了 initForm() 吗?你能用 console.log() 确认吗?
  • 我认为您的 tinvoiceService 存在严重问题。你为什么要在那里初始化表单?它不应该在你的组件中吗?

标签: angular angular-reactive-forms angular2-formbuilder formarray angular-formbuilder


【解决方案1】:

老问题,但会给出我的看法

当用户点击编辑按钮时,控制台日志工作指示

找不到名称为:购买的表单控件

所以我们从这里开始,找出行中的问题

  this.form.setValue(invoice) 

如果我们此时记录invoice 的值,我们会看到

{
    "createdAt": "Mon May 10 2021 15:32:51 GMT+0100 (UTC+01:00)",
    "customer": {
        "address": "s",
        "lastname": "Perez",
        "name": "Carlos ",
        "phone": "7861236589"
    },
    "purchases": [
        {
            "product": {
                "categoryS": "-MZyCBHUjLrfxzoRdZBM",
                "location": "Store",
                "name": "TV Samsung",
                "price": 50
            },
            "quantity": 1
        }
    ],
    "totalPrice": 50,
    "$key": "-M_LgTlysUg07lHdjtuG"
}

如果我们记录 this.form.value 的值,我们 aee

{
    "customer": {
        "name": null,
        "lastname": null,
        "address": null,
        "phone": null
    },
    "createdAt": null
}

所以你试图为表单分配一个不正确的对象结构。

要检查您的代码是否真正工作,您只需将setValue 更改为patchValue。以下解决方案的工作原理是 patchValue 只会查找与 setValue 不同的表单控件。另一方面,要使用 setValue,您必须确保对象中的所有属性都在 FormGroup 中表示,否则从对象中删除这些属性

下面是Demo,通过将setValue 更改为patchValue 来显示解决方案

【讨论】:

    【解决方案2】:

    Form 是一个 UI 元素,它在视图渲染后被实例化。

    你可以尝试在ngAfterViewInit调用这个函数,错误应该消失了。如果不只是创建一个小提琴,我会尝试为您修复它。

    【讨论】:

    • 他在这里创建了一个响应式表单。所以这不是真的。在他的情况下也可以在ngOnInit 中完成。
    • @MehuIJoshi 添加与 StackBlitz 的链接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2018-08-29
    • 2018-08-07
    • 2018-10-29
    • 2018-11-08
    相关资源
    最近更新 更多