angularangular-materialngfor

How to I create a Mat-Step with for loop which has individual components inside?


I have around 20 forms created as difference components and implemented with mat-stepper as below

<mat-step>
    <form [formGroup]="form1">
      <component1></component1>
    </form>
    <div>
      <button  matStepperNext >Next</button>
    </div>
  </mat-step>

<mat-step>
    <form [formGroup]="form1">
      <component2></component2>
    </form>
    <div>
      <button  matStepperNext >Next</button>
    </div>
  </mat-step>

.
.
.
.
.
<mat-step>
    <form [formGroup]="form1">
      <component20></component20>
    </form>
    <div>
      <button matStepperNext >Next</button>
    </div>
  </mat-step>

how do i create this using *ngFor?


Solution

  • First create an array, with each component in the TS file.

    components = [
        { form: this.form1, component: Component1 },
        { form: this.form1, component: Component2 },
        { form: this.form1, component: Component3 },
        ...
    
        ...
        { form: this.form1, component: Component20 },
    ];
    

    Then we can use ngComponentOutlet to create the component dynamically. You may need to provide an injector or a module as input, for the component to work correctly. Since no code shared on this, please go through the docs to learn more.

    <mat-stepper [linear]="isLinear" #stepper>
      <mat-step [stepControl]="data.form" *ngFor="let data of components">
        <form [formGroup]="data.form">
           <ng-container *ngComponentOutlet="data.component"></ng-container>
          <div>
            <button mat-button matStepperNext>Next</button>
          </div>
        </form>
      </mat-step>
    </mat-stepper>