【问题标题】:Changes To FormGroup.value edit the actual formGroup controls更改 FormGroup.value 编辑实际的 formGroup 控件
【发布时间】:2021-06-29 11:00:05
【问题描述】:

我有一个包含大约 20 个控件的 formGroup。其中 2 个是日期对象。

我想将整个 formGroup 转换为一个对象,其中 2 个日期控件转换为 ISOString

但是,当我转换日期时,原始 formGroup 的控件值也会更新。有什么想法可以转换formGroup.value 的属性并修改该对象而不影响原始对象吗?

prepareParams():ReportRequest{
  let query = this.reportForm.value
  if(query.startDate)
    query.startDate = this.reportForm.get('startDate')?.value.toISOString()
  if(query.endDate)
    query.endDate = this.reportForm.get('endDate')?.value.toISOString()
  return query
}

【问题讨论】:

    标签: angular formgroups


    【解决方案1】:

    您可以使用扩展运算符或Object.assign 克隆表单的值对象。否则,您将更新表单的值,因为变量 query 将只是对原始对象的另一个引用。

    类似这样的:

    prepareParams():ReportRequest{
      let query = { ...this.reportForm.value };
      if(query.startDate)
        query.startDate = this.reportForm.get('startDate')?.value.toISOString()
      if(query.endDate)
        query.endDate = this.reportForm.get('endDate')?.value.toISOString()
      return query
    }
    

    或者这个:

    prepareParams():ReportRequest{
      let query = Object.assign({}, this.reportForm.value);
      if(query.startDate)
        query.startDate = this.reportForm.get('startDate')?.value.toISOString()
      if(query.endDate)
        query.endDate = this.reportForm.get('endDate')?.value.toISOString()
      return query
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-15
      • 2012-05-10
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多