Mastering Angular Mat-Stepper: A Step-by-Step Guide to Updating mat-step According to Your Route Link
Image by Khloe - hkhazo.biz.id

Mastering Angular Mat-Stepper: A Step-by-Step Guide to Updating mat-step According to Your Route Link

Posted on

Are you tired of struggling with the Angular Material Stepper (mat-stepper) and wondering how to update the mat-step according to your route link? Look no further! In this comprehensive guide, we’ll take you on a journey to conquer the Angular Material Stepper and make it do your bidding.

What is Angular Material Stepper?

The Angular Material Stepper (mat-stepper) is a UI component that allows users to navigate through a series of steps, providing a linear workflow experience. It’s commonly used in wizards, onboarding processes, and other interactive elements.

Updating the mat-step according to your route link is essential for creating a seamless user experience. Imagine a scenario where a user clicks on a link, and the stepper automatically navigates to the corresponding step. It’s like magic, right? This approach enhances user engagement, reduces friction, and makes your application more intuitive.

Pre-requisites

Before we dive into the implementation, make sure you have:

  • Angular 9+ installed
  • Angular Material 9+ installed
  • A basic understanding of Angular and Angular Material

Step 1: Set up the Mat-Stepper

Create a new Angular component and add the following HTML code:

<mat-horizontal-stepper>
  <mat-step [stepControl]="step1">
    <ng-template matStepLabel>Step 1</ng-template>
    <p>This is step 1</p>
  </mat-step>
  <mat-step [stepControl]="step2">
    <ng-template matStepLabel>Step 2</ng-template>
    <p>This is step 2</p>
  </mat-step>
  <mat-step [stepControl]="step3">
    <ng-template matStepLabel>Step 3</ng-template>
    <p>This is step 3</p>
  </mat-step>
</mat-horizontal-stepper>

In the component’s TypeScript file, add the following code:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-stepper',
  templateUrl: './stepper.component.html',
  styleUrls: ['./stepper.component.css']
})
export class StepperComponent {
  step1: FormGroup;
  step2: FormGroup;
  step3: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.step1 = this.formBuilder.group({
      step1Control: ['']
    });
    this.step2 = this.formBuilder.group({
      step2Control: ['']
    });
    this.step3 = this.formBuilder.group({
      step3Control: ['']
    });
  }
}

Create a new Angular component and add the following HTML code:

<nav>
  <a [routerLink]="['/step1']">Go to Step 1</a>
  <a [routerLink]="['/step2']">Go to Step 2</a>
  <a [routerLink]="['/step3']">Go to Step 3</a>
</nav>

In the component’s TypeScript file, add the following code:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent {
  constructor(private router: Router) { }
}

In the StepperComponent, add the following code:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-stepper',
  templateUrl: './stepper.component.html',
  styleUrls: ['./stepper.component.css']
})
export class StepperComponent implements OnInit {
  step1: FormGroup;
  step2: FormGroup;
  step3: FormGroup;

  constructor(private formBuilder: FormBuilder, private router: Router) { }

  ngOnInit(): void {
    this.step1 = this.formBuilder.group({
      step1Control: ['']
    });
    this.step2 = this.formBuilder.group({
      step2Control: ['']
    });
    this.step3 = this.formBuilder.group({
      step3Control: ['']
    });

    this.router.events.subscribe((event: any) => {
      if (event.url) {
        const urlParts = event.url.split('/');
        const stepIndex = urlParts[urlParts.length - 1];

        switch (stepIndex) {
          case 'step1':
            this.selectStep(0);
            break;
          case 'step2':
            this.selectStep(1);
            break;
          case 'step3':
            this.selectStep(2);
            break;
        }
      }
    });
  }

  selectStep(index: number) {
    // Update the mat-step according to the selected index
    (this.stepper)._steps.toArray()[index].classList.add('mat-step-active');
  }
}

In the above code, we’re listening to the router events and extracting the last part of the URL. We’re then using a switch statement to determine which step to select based on the URL.

Step 4: Add Routing Configuration

In the app-routing.module.ts file, add the following code:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { StepperComponent } from './stepper/stepper.component';

const routes: Routes = [
  { path: 'step1', component: StepperComponent },
  { path: 'step2', component: StepperComponent },
  { path: 'step3', component: StepperComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

In the above code, we’re configuring the routes to point to the StepperComponent for each step.

Conclusion

VoilĂ ! You’ve successfully implemented the Angular Material Stepper to update the mat-step according to your route link. With this comprehensive guide, you should now have a seamless user experience that enhances engagement and reduces friction.

Common Issues and Solutions

If you encounter any issues, refer to the following troubleshooting guide:

Issue Solution
mat-step not updating Check that the router events are being triggered correctly and the stepIndex is being updated correctly.
Route links not working Verify that the routing configuration is correct and the StepperComponent is being correctly routed to.

Final Thoughts

Mastering the Angular Material Stepper is a crucial step in creating engaging and user-friendly applications. By following this guide, you’ve taken a significant step forward in enhancing your application’s usability and user experience.

Remember, practice makes perfect. Experiment with different scenarios, and don’t hesitate to reach out if you have any questions or need further assistance.

Happy coding, and may the Angular Material Stepper be with you!

Here are 5 Questions and Answers about “Angular Mat-stepper how to update the mat-step according to the route link”:

Frequently Asked Question

Stuck on updating your mat-step according to the route link in Angular Mat-stepper? Don’t worry, we’ve got you covered! Here are some frequently asked questions to help you out.

How do I update the mat-step when the route changes?

You can use the router’s navigation events to update the mat-step. Inject the router in your component and subscribe to the navigationEnd event. Then, update the mat-step accordingly based on the current route.

Can I use a service to update the mat-step?

Yes, you can create a service that updates the mat-step based on the current route. This way, you can share the service across components and keep your code organized.

How do I get the current route parameter in my component?

You can use the ActivatedRoute service to get the current route parameter. Inject the ActivatedRoute in your component and access the params property to get the current route parameter.

Can I update the mat-step programmatically?

Yes, you can update the mat-step programmatically by calling the stepper’s selectedIndex property and setting it to the desired index. You can also use the stepper’s next() or previous() methods to navigate to the next or previous step.

How do I handle multiple stepper instances on the same page?

You can handle multiple stepper instances by using a unique identifier for each stepper. Then, update the corresponding stepper instance based on the current route and identifier.

Leave a Reply

Your email address will not be published. Required fields are marked *