/ Web

Angular FormBuilder group unexpectedly change array to value

Problem

Component editor receives an object and create reactive form base on the object passed in.

Something like this(most fields are omitted):

this.form = new FormBuilder().group({
      id: this.postObj.id,
      tags: this.postObj.tags,
    });

But you will realise the tags field does not really behave like what you wanted(well, at least not what I was expecting)

Pass in:

{
	id:1,
	tags:[3]
}

By viewing value of the form, you will see you actually get:

{
	id:1,
	tags:1
}

WAIT Why my tags become an value instead of an array?

What I expected is(same as what I pass in):

{
	id:1,
	tags:[3]
}

This will cause your select control out of order as they typically needs an array data structure to hold their value.

Solution

Take a look at the reactive form document on Angular website.

https://angular.io/guide/reactive-forms

Especially this part:

profileForm = this.fb.group({
    firstName: [''],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
  });

So the form group needs you pass in the value in side an array(not sure what the reason is, please let me know in comment if you do know about it)

Now we rewrite our builder code to be like this:

this.form = new FormBuilder().group({
      id: [this.postObj.id],
      tags: [this.postObj.tags],
    });

YAY! Problem solved!

mimimi

mimimi

Currently a Computer Engineering student at the National University of Singapore, passionate about software engineering. Contact me: info at mimimi.fun

Read More
Angular FormBuilder group unexpectedly change array to value
Share this