Search code examples
angularformsnestedngmodel

How to set unique name to ngModelGroup in the form on different places


I have a Component, the selector is: app-common-component.

The app-common-component based on an ngModelGroup :

<fieldset ngModelGroup>
</fieldset>

I have a form, which separated to two components app-component-a and app-component-b

<form>
  <app-component-a></app-component-a>
  <app-component-b></app-component-b>
</form>

The app-component-a contains the app-common-component

<fieldset ngModelGroup="componenta">
  <app-common-component></app-common-component>
</fieldset>

The app-component-b contains the app-common-component also

<fieldset ngModelGroup="componentb">
  <app-common-component></app-common-component>
</fieldset>

My question is how can I set the ngModelGroup name of the app-common-component in different places?

I would like to see below the form the following:

mainForm
  controls
    componenta
      controls
        unique name of the app-common-component
    componentb
      controls
        unique name of the app-common-component

Solution

  • As mentioned by Andrei you can use Input property to set unique name or you can set global varibale inside common component. Then increment it by 1 for every newinstance something like this.

    common.component.ts

    let uniqueId = 0;
    
    @Component({
      selector: 'app-common-component',
      template: `
       <fieldset [ngModelGroup]="groupName">
       </fieldset>
      `,
    })
    export class AppCommonComponent  {
      groupName = uniqueId++; 
    
    }