2

I have some problems with my mat-stepper, where each step is a new component.

My problem is that ngOnDestroy() is not being triggered on each steps (components), when going back and forth in my mat-stepper.

My stepper is as follows: HTML:

<mat-horizontal-stepper [selectedIndex]="selectedIndex" linear labelPosition="bottom" #stepper fxLayoutAlign="center center" fxLayout="column">
    <mat-step [stepControl]="step1">
        <ng-template matStepLabel>{{ stepCaptions[0] }}</ng-template>
        <app-step1></app-step1>
    </mat-step>
    <mat-step [stepControl]="step2">
        <ng-template matStepLabel>{{ stepCaptions[1] }}</ng-template>
        <app-step2></app-step2>
    </mat-step>
    <mat-step [stepControl]="step3">
        <ng-template matStepLabel>{{ stepCaptions[2] }}</ng-template>
        <app-step3></app-step3>
    </mat-step>
    <mat-step [stepControl]="step4">
        <ng-template matStepLabel>{{ stepCaptions[3] }}</ng-template>
        <app-step4></app-step4>
    </mat-step>
    <mat-step [stepControl]="step5">
        <ng-template matStepLabel>{{ stepCaptions[4] }}</ng-template>
        <app-step5></app-step5>
    </mat-step>
</mat-horizontal-stepper>

Typescript:

@ViewChild('stepper', { static: false }) stepper;

Am I missing something?

1 Answers1

2

You could use *ngIf with the selectedIndex on your components to force ngOnDestroy() on your app-step components.

<mat-horizontal-stepper [selectedIndex]="selectedIndex" linear labelPosition="bottom" #stepper fxLayoutAlign="center center" fxLayout="column">
    <mat-step [stepControl]="step1">
        <ng-template matStepLabel>{{ stepCaptions[0] }}</ng-template>
        <app-step1 *ngIf="selectedIndex === 0"></app-step1>
    </mat-step>
    ...
</mat-horizontal-stepper>
famenev
  • 256
  • 2
  • 3
  • 1
    So if the value of "selectedIndex" is turning into another value than 0, then the step1 component is going to be destroyed? – Thomas Leo Blok Sep 18 '20 at 12:08
  • 1
    Yes so you should probably use the `selectionChange` output of mat-stepper to update your selectedIndex. – famenev Sep 18 '20 at 12:13