dynamic formGroup within formArray using formBuilder angular 2

耗尽温柔 提交于 2021-01-27 20:05:11

问题


I have an array on my backend called media that stores several objects. It looks something like this:

"media": [
    {
        "srcId": null;
        "primary": false,
        "thumbs": {
            "default": null
        },
        "type": null,
        "raw": null
    }
]

My edit-component.ts for the loading this array into the form looks like this:

  media: this._fb.array([
    this._fb.group({
      srcId: new FormControl(this.existingMedia.srcId),
      type: new FormControl(this.existingMedia.type),
      raw: new FormControl(this.existingMedia.raw),
      primary: new FormControl(this.existingMedia.primary),
      thumbs: this._fb.group({
        default: new FormControl(this.existingMedia.thumb.default)
      })
    })
  ]),

Right now this will load the first object from that media array but not other media objects that could be in the array. Is there a way to make the formBuilder group inside the formArray Media dynamic to the number of objects within the Media Array on the backend?

Any help/tips/suggestions would be much appreciated!

Update

In my ngOnInit I have:

  this.currentCard = selectedCurrentCard;
  for (let medias of this.currentCard.media){
    this.existingMedia = medias;

to iterate over my media array on the backend and

  const control = <FormArray>this.cardForm.controls['media'];
    control.push(this.initCurerntMedia()); 

with initCurrentMedia() looking like this: UPDATED initCurrentMedia() this updated version worked when called in ngOnInit() Thanks to the help of @AJT_82

initCurrentMedia() {
    this.currentCard.media.forEach(media => {
      const control = <FormArray>this.cardForm.controls['media'];
      control.push(
        this._fb.group({
          srcId: new FormControl(media.srcId),
          type: new FormControl(media.type),
          raw: new FormControl(media.raw),
          primary: new FormControl(media.primary),
          thumbs: this._fb.group({
            default: new FormControl()
          })
        })
      )
    })
  }

To populate my form with current media. It is still only populating one object.


回答1:


I like to build the form

this.myForm = this._fb.group({
  media: this._fb.array([])
})

and then after response have been fetched set the values, so after getting the response you can call a method, let's say setForm():

setForm() {
  this.media.forEach(x => {
    this.myForm.controls.media.push(
      this._fb.group({
        srcId: x.srcId,
        type: x.type,
        raw: x.raw,
        primary: x.primary,
        thumbs: this._fb.group({
          default: x.thumbs.default
        })        
      )
    })
  })
}


来源:https://stackoverflow.com/questions/45194341/dynamic-formgroup-within-formarray-using-formbuilder-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!