Paul Mullen
Paul Mullen

Reputation: 47

Angular/Ionic FormGroup, FormArray, FormBuilder... I'm lost

Use case: This is an inventory update page for a coffee shop.

enter image description here

An inventory item is defined like this:

interface InventoryData {
  category: string;
  current: number;
  id: string;
  name: string;
  par: number;
  units: string;
  previous?: string;
  supplier: string;
  notes?: string;
}

On this page, I'm only manipulating the current level and the notes? for each item.

At the bottom of the form, I have an ion-textarea that is a space for the associates to write anything that the managers should know.

enter image description here

So the structure of the page is

HEADER
   SECTION HEADERS ENTERED AUTOMATICALLY ON CHANGE OF CATEGORY

      ITEM[0]                                  <-+
          [ITEM DETAILS]                         |
          [INPUT CURRENT QUANTITY]               |
          [INPUT NOTES]                          |--- Array of similar items with
      ITEM[1]...                                 |    inputs for quantity and notes
      ITEM[2]...                                 |    for each
                                                 |
      ITEM[n]                                  <-+

  GENERAL NOTES SECTION                <---- not part of an item... overall info.

FOOTER

I have tried setting up the page has having two separate forms, one for the inventory items and one for the general notes at the end. Something like this:

  inventoryForm = this.fb.group({
    items: this.fb.array([]),
  });

  notesForm = this.nb.group({
    notes: [''],
  });

And I have tried setting it up as a single form that has the array items plus one additional form field for the general notes.

But it all seems very messy.

So I'm hoping to learn how experienced people would do this. This is more of a strategy question than a coding question, but I'd be thrilled with advice from either direction.

Upvotes: 1

Views: 370

Answers (1)

vaira
vaira

Reputation: 2270

Usually when in such a conflicting state I ask myself:

  1. Does the data go back in a single API? (No means heavily lean towards two form)
  2. Does updating value in one can impact (validate) the other form. (Yes heavily lean towards a single form, No means lean towards two form)
  3. Is component reusability making an impact. (you can also create reusable form components in angular)

In your case, if both from are submitted together with a single button in a single API then it should be a single form.

It might look messy if you are writing a lot of code in a single component. You can always divide the code as much as possible.

 inventoryForm = this.fb.group({
    items: this.fb.array([]),
    notes: [''],
  }); 

Just an observation: Your note area looks more like a comment area.

Upvotes: 2

Related Questions