1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

How can I populate a ngModelGroup with content projection?

Discussão em 'Angular' iniciado por PedroHC, Junho 25, 2025.

  1. PedroHC

    PedroHC Guest

    I'm trying to create a component that uses the ngModelGroup to group some inputs inside a ngForm. I noticed that when using the ngModelGroup directly inside the form it works as expected:

    <form #form="ngForm">
    <div ngModelGroup="personalInfo">
    <input type="string" ngModel name="firstName">
    <input type="string" ngModel name="lastName">
    </div>
    </form>
    <pre>{{form.value | json}}</pre>


    This creates the following form structure, as expected:

    {
    "personalInfo": {
    "firstName": "",
    "lastName": ""
    }
    }


    However, I need to create a component where the inputs are projected inside it:

    @Component({
    selector: 'app-component-with-the-ngmodelgroup-inside',
    template: `
    <div #group="ngModelGroup" [ngModelGroup]="groupName">
    <ng-content></ng-content>
    </div>
    `,
    imports: [CommonModule, FormsModule],
    standalone: true,
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm }],
    })
    export class ComponentWithNgModelGroupComponent {
    @Input() groupName: string = '';
    }


    Using the component, then, looks like this:

    <form #form="ngForm">
    <app-component-with-the-ngmodelgroup-inside groupName="perfonalInfo">
    <input type="string" ngModel name="firstName">
    <input type="string" ngModel name="lastName">
    </app-component-with-the-ngmodelgroup-inside>
    </form>
    <pre>{{form.value | json}}</pre>


    In this case the form.value structure is left like this:

    {
    "firstName": "",
    "lastName": ""
    "personalInfo": {},
    }


    How could I handle the projected content so that the form controls are correctly registered inside the ngModelGroup?

    Continue reading...

Compartilhe esta Página