【问题标题】:Unable to setValue into reactive forms for second time after resetting the form重置表单后无法第二次将值设置为反应式表单
【发布时间】:2019-10-26 05:07:50
【问题描述】:

使用响应式表单,当我们点击编辑特定用户时,使用 setValue 方法填充到表单控件中。然后当我点击保存按钮时,我正在使用 reset() 方法清除表单。

现在,如果单击另一个用户的编辑按钮,我将填充与上述相同的数据,但 setValue 或 patchValue 不会将数据添加到表单字段中

https://stackblitz.com/edit/angular-dzyjig

【问题讨论】:

标签: angular


【解决方案1】:

您的问题与Change Detection有关。

您的代码有问题:

您正在将值从父组件发送到子组件,并且您正在调用 ngOnChanges 内的 edit 方法,该方法将在 Angular 更改检测期间运行。

在您的父组件edit 方法中,您有:

edit(user){
   this.user = user;
   console.log(this.user);
}

现在如果你点击同一个用户编辑按钮,this.user 不会改变,也不会触发你的子组件的ngOnChanges 方法,你的表单也不会被填充。

解决方案:(你可以找到工作的stackbliz演示here )

即使您单击同一个用户编辑按钮并手动触发更改检测,您也需要每次更改用户的值。

import { Component } from '@angular/core';
import { FormGroup, Validators, FormBuilder} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(private formBuilder: FormBuilder, private cd: ChangeDetectorRef){
  }

  edit(user){
    this.user = null;
    this.cd.detectChanges();
   this.user = user;
   console.log(this.user);
  }
}

您的ngOnChanges 将如下所示:

ngOnChanges(){
    if(this.user) {
      this.edit();
    }
  }

希望对你有帮助。

【讨论】:

  • ngOnChanges(){ if(this.editableProduct){ this.EditProductData(); } } EditProductData(){ if(!!this.editableProduct && !!this.editableProduct.productToEdit){ this.PDForm.patchValue({ productIDName: this.editableProduct.productToEdit.productIDName, moq: this.editableProduct.productToEdit.moq } ) } }
  • 在 EditProductDatamethod 中,我正在获取 this.editableProduct 数据,但它没有第二次将数据填充到表单字段中。
  • 你看到我在回答中提供的演示了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 2021-11-25
  • 1970-01-01
相关资源
最近更新 更多