angular material open last visited tab 1

angular material open last visited tab

constructor(private route: ActivatedRoute,
  private router: Router) {}

selectedTabIndex: number;

ngOnInit(): void {
  this.selectedTabIndex = parseInt(this.route.snapshot.queryParamMap.get('tab'), 10);
  // TODO: check upper bound. Material will set the last tab as selected
  // if selectedTabIndex >= number of tabs
  if (isNaN(this.selectedTabIndex) || this.selectedTabIndex < 0) {
    this.selectedTabIndex = 0;
  }
}

onTabChange(selectedTabIndex: number): void {
  this.router.navigate([], { relativeTo: this.route, queryParams: {
    tab: selectedTabIndex
  }});
  this.selectedTabIndex = selectedTabIndex;
}

Here is what the above code is Doing:
1. The component is subscribing to the query params in the URL.
2. The component is setting the selectedTabIndex to the value of the tab query param.
3. The component is setting the selectedTabIndex to 0 if the tab query param is not present or is not a number.
4. The component is setting the tab query param to the selectedTabIndex when the tab changes.

Similar Posts