Multiple NgModelGroup nesting across different components

Issue

When I try to nest NgModelGroup inside another NgModelGroup, it looks like Angular just ignore it. I’m using Angular 12 and Template-driven Forms.

This is how my code looks like:

app.component.html

<form #form="ngForm">
  <div class="col-auto">
    <input name="name" id="name" ngModel /><br />
    <app-address></app-address>
  </div>
  <div class="btn-toolbar">
    <button type="submit" (click)="submit(form)">Submit</button>
  </div>
  <p>{{ form.value | json }}</p>
</form>

address.component.html

<div ngModelGroup="address">
  <input name="street" id="street" ngModel />
  <app-contact></app-contact>
</div>

contact.component.html

<div ngModelGroup="contact">
  <input name="phone" id="phone" ngModel />
</div>

This is the actual result:

{
   "name":"John Snow",
   "address":{
      "street":"201 Somewhere Place, 12"
   },
   "contact":{
      "phone":"6405106300"
   }
}

And this is what I’m trying to get unsuccessfully:

{
   "name":"John Snow",
   "address":{
      "street":"201 Somewhere Place, 12",
      "contact":{
         "phone":"6405106300"
      }
   }
}

Also, you can see the code here: https://stackblitz.com/edit/angular-ivy-osf83a?

Solution

The problem was solved changing the NgForm to NgModelGroup on my Contact typescript file.

import { Component, OnInit } from '@angular/core';
import { ControlContainer, NgModelGroup } from '@angular/forms';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: NgModelGroup }],
})
export class ContactComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

This is what it looks like before. Note that I just have to change two places:

import { Component, OnInit } from '@angular/core';
import { ControlContainer, NgForm } from '@angular/forms';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: NgForm }],
})
export class ContactComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

Answered By – Pankwood

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.