【问题标题】:Angular Reactive Forms - Repeat objectsAngular Reactive Forms - 重复对象
【发布时间】:2021-01-08 00:18:32
【问题描述】:

我是 Angular 10 的新手(从 Angularjs 跳到 Angular),我遇到了一些问题

我在数据库中有多个这样的对象:

{
  "id" : 1,
  "search_name" : "example search name",
  "link" : "https://link",
  "label": {
    "label_uk" : "UK Label",
    "label_us" : "US Label",
    },
  "description" : {
    "description_uk": "",
    "description_us":""
  }
}

我正在尝试为每个对象构建一个重复表单,因此对于每个键我需要在表单中进行编辑: 示例:

formGroup.addControl('link', new FormControl(object.link));

我的问题:如何在不为其创建控件的情况下保留 id(因为我不会编辑它)? 我应该为模型中的每个键创建控件吗? (我只想编辑一些) 如何知道我的模型?

谢谢你,如果我的问题不清楚,对不起!

【问题讨论】:

  • 由于您使用的是响应式表单,因此即使您不打算更改,也可以创建 formControl。这样关联的值将被组合在一个 formGroup 中。
  • 所以如果我有一个大对象,例如有 40 个键,并且我想编辑其中的 5 个,我应该在我的 formGroup 中创建 40 个控件?谢谢
  • 您想在 UI 中显示所有 40 个按键控件吗?
  • 不是全部,但我想将一些键用于其他内容,例如显示标题或使用 href 创建链接...但不作为表单控件(输入、选择...)
  • 然后可以将id存储在formGroup中,然后根据formGroup id控件映射对象。

标签: angular angular-reactive-forms angular10


【解决方案1】:

您可以选择这两种方法,创建一个具有所有“属性”的 FormGroup 的好处,允许您在创建新的“对象”时使用相同的 FormGroup。

例如一个功能,如

getFormGroup(data:any=null)
{
   data=data || {id : 0, search_name : null,link:null,label:null,description:null}
   return new FormGroup({
      id:new FormControl(data.id),
      search_name:new FormControl(data.search_name),
      link:new FormControl(data.link),
      label:data.label?new FormGroup({
          label_uk:new FormControl(data.label.label_uk),
          label_us:new FormControl(data.label.label_us),
      }):
                       new FormGroup({
          label_uk:new FormControl(null),
          label_us:new FormControl(null),
      })
      description:data.description?new FormGroup({
          description_uk:new FormControl(data.description.description_uk),
          description_us:new FormControl(data.description.description_us),
      }):
                       new FormGroup({
          description_uk:new FormControl(null),
          description_us:new FormControl(null),
      })
     
   })
}

允许您使用创建表单组

this.myForm=this.getFormGroup()  //an empty
this.myForm=this.getFormGroup(this.data)  //a data

但是,正如你所说,你有一个包含 40 个字段的对象,而你只需要更改其中的 5 个。您可以使用两个功能

getNewFormGroup(){
   this.state="new"
   return .....
}

getUpdateFormGroup(data){
      this.state="update"
      return new FormGroup({
          search_name:new FormControl(data.search_name),
          link:new FormControl(data.link),
          label:new FormGroup({
              label_uk:new FormControl(data.label.label_uk),
              label_us:new FormControl(data.label.label_us),
          })
}

记住一个 FormGroup(如果你没有 html 输入,他的值存在事件)

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 1970-01-01
    • 2023-04-06
    • 2019-08-13
    • 2020-07-24
    • 2021-10-23
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    相关资源
    最近更新 更多