Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nested objects in FormBuilder

So I have this form, and it works fine.. but now I would like to extend the json structure some...

https://plnkr.co/edit/aYaYTBRHekHzyS0M7HDM?p=preview

The new structure I want to use looks like this (only address: has changed):

  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(5)]],
  address: this.fb.array([{
    name: '',
    addressLine1: ['', [Validators.required]],
    city: ['', [Validators.required]],
    postalCode: [Validators.required],
  }]),

But I keep getting errors like "ERROR TypeError: control.registerOnChange is not a function". Figured out that this has to do with formControlName missing but I don´t want all data do show..

In the input field I only want addressLine1 to show (not showing name, city, or postalCode at all).

like image 727
Mackelito Avatar asked Jun 01 '17 12:06

Mackelito


People also ask

How do you use formControlName and deal with nested FormGroup?

With a parent FormGroup, the name input needs the syntax formControlName=name in order to be associated with the correct FormControl in the class. This syntax tells Angular to look for the parent FormGroup, in this case heroForm, and then inside that group to look for a FormControl called name.

What is difference between FormBuilder and FormControl?

In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.

How do I use FormArray in FormBuilder?

First, we need to import the FormArray from the Angular Forms Module. Build a formGroup orderForm using the FormBuilder. We define items as FormArray. We need to capture two fields under each item, the name of the item & description and price.


Video Answer


1 Answers

I would use a form group instead of a formarray for the address, so it would look like this instead:

this.registrationForm = fb.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(5)]],
  address: this.fb.group({ // make a nested group
    name: '',
    addressLine1: ['', [Validators.required]],
    city: ['', [Validators.required]],
    postalCode: [Validators.required],
  }),
});

Then in your template, remember to mark the formGroupName:

<md-input-container formGroupName="address"> <!-- Mark the nested formgroup name -->
   <input mdInput type="text" placeholder="AddressLine1" name="address" 
         formControlName="addressLine1" fodiGoogleplace 
         (updateAdress)="setAdressOnChange($event)">
</md-input-container>

Your forked PLUNKER

like image 161
AT82 Avatar answered Nov 07 '22 19:11

AT82