Search code examples
angularbind

How to bind nested object within Form?


I bind data received from an API to a Form this way:

 // json data
 export class Recipe {
    _id: String;
    nome: String;
    tipo: Number;
    panetti: Number;
 }

 // ts (load data from API)
 this.form = this.fb.group({
    nome: [data.nome, [Validators.required]],
    tipo: [data.tipo, [Validators.required]],
    panetti: [data.panetti, [Validators.required]]
 });
 
 // component
 <mat-form-field>
    <input matInput type="text" formControlName="nome">
 </mat-form-field>

but how can I do the same if the object become complex? Such as:

 // json data
 export class Recipe {
    _id: String;
    nome: String;
    tipo: Number;
    panetti: Number;
    ingredienti: {
        newField1: Number,
        newField2: Number,
        newArray: [
            {
                arrayField1: Number,
                arrayField2: Number
            }
        ];
    }
 }

how can I bind in this case newField1 and newArray/arrayField*?


Solution

  • For 'ingredienti' you'll have another form group. Something like

     this.form = this.fb.group({
      nome: [data.nome, [Validators.required]],
      tipo: [data.tipo, [Validators.required]],
      panetti: [data.panetti, [Validators.required]],
      ingredienti: this.fb.group({
        newField: ['initialValue'],
        secondField: ['initialValue'],
      })
    });
    

    And if you have a dynamic array field, for 'newArray' you could use FormArray. Take a look here https://angular.io/api/forms/FormArray.

    Edit for Markzz comment: On your html form tag you're using [formGroup]="form". Inside of it (where do you want to display the rest of fields), you're using 'formGroupName'. (ideally using with ng-container because it's not rendered to the dom).