How to destroy components in mat-stepper

1.3k views Asked by At

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?

2

There are 2 answers

2
famenev On

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>
0
Jay Querido On

Closely related -- and maybe helpful to some -- is the MatStepContent directive.

It will lazy load the contents only when the stepper progresses to that step.

NOTE: This directive does not affect the unloading/destruction of any nodes it affects.

<mat-stepper>

    <mat-step label="Eagerly loaded contents">
        This will load immediately when the component loads.
    </mat-step>

    <mat-step label="Lazy loaded contents">
        <ng-template matStepContent>
            This text and image will only load once the user first visits step two.
            <img src="/img/blerg.png" />
        </ng-template>
    </mat-step>

    <mat-step label="Eagerly loaded contents">
        This will also load immediately when the component loads.
    </mat-step>

</mat-stepper>