javascriptangularangular-routingmat-stepper

Browser back and forward button for each step in Angular material Stepper


I have a stepper that loads child components.

I want the user to be able to press the browsers back and forward button when they want to go back or forward a step.

My guess is using the Location service in @angular/common and storing it the history.

import { Component, OnInit, ViewChild} from '@angular/core';
import { Location } from '@angular/common';

@Component({
  selector: 'app-vehicle',
  templateUrl: './vehicle.component.html',
  styleUrls: ['./vehicle.component.css']
}) 

export class VehicleComponent implements OnInit {
@ViewChild('stepper') stepper;

ngOnInit() {
  this.location.subscribe(x => {
  this.stepper.selectedIndex = this.stepper.selectedIndex -1;
 });
}

// this adds that path to the url. I dont use path changes as params.
onVehClick() {
this.location.go(this.location.path() + '/vehicle');
 }

onTypeclick() {
this.location.go(this.location.path() + '/vehicle/jetski');
 }
}

This works but I get an error in the console log

Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'service/vehicle/'

This is because there is no route, it's cosmetic and serves only the purpose of pressing the browsers back button.

  1. Can I have functionality like this without parsing the URL checking for the params I used? My guess is you do.

  2. The forward button doesn't work because of the same reason i get an error with the back button. Im starting to think they only way to have the forward is take the path as query params. is this true?

  3. Can i somehow stop the forward button or redirect it somewhere else?

In fact, all i want is to make the back button or forward button doesn't leave that vehicle component.


Solution

  • Without using query params in the url you would have to check for the url for which vehicle and compare it on the string value. Unfortunately there couldn't be query params in this instance

    I more or less did little shortcuts the would just redirect me back to path of the component. So on refresh, back and forward button the path redirects to just vehicle path. Here is my routing module:

      {path: 'vehicle/:vehType', pathMatch: 'full', redirectTo: 'vehicle'},