Redirect in a specified tab in another page from link Angular 6

痞子三分冷 提交于 2020-01-02 10:28:12

问题


I'm working with Angular 6.2 & Angular Material.

I have a page with mat tabs (3 tabs).

It is possible to redirect in this page but with the 3rd tab active? From clicking a link in the navbar.

It looks like not possible, there isn't any solution for this on websites.


回答1:


If you are using a mat-tab-group, there is an input property to specify the index of the active tab.

@Input() selectedIndex: number | null => The index of the active tab.

Refer the Official docs for mat tab groups




回答2:


I found a good solution:

I use queryParams

<a routerLink="/account" [queryParams]="{ tab: 'notifications'}">Link</a>

Then I set my tab active if there is tab & it's value = notifications:

[active]="tab && tab === 'notifications'"

In the controller I set tab (this.tab) if there is queryparams and I remove it so I never see

?tab=notifications

in my URL.

ngOnInit() {
  this.activatedRoute.queryParams.subscribe((params) => {
    if (params.tab) {
      this.tab = params.tab;
      this.route.navigate([], {
        queryParams: {
          tab: null,
        },
        queryParamsHandling: 'merge',
      });
    }
  });
}



回答3:


Here is a solution using the Location service that is not using the Angular Router and that listens to the hash fragment in the route and sets the selectedIndex to it, that way, the tabs content are all loaded in the same page but the activeTab will match the fragment set in the route.

The links to to go to the page and activate a tab would be /my-page#0, /my-page#1...

Here is a stackblitz: https://stackblitz.com/edit/mat-tab-sync-with-hash-fragment

import { Component } from '@angular/core';
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers: [Location, { provide: LocationStrategy, useClass: PathLocationStrategy }]
})
export class AppComponent  {
  name = 'Angular';
  selectedIndex = 0;

  constructor(private location: Location) {
    this.selectedIndex = (+this.location.path(true).substr(1) - 1) || 0;
    this.location.subscribe((value: PopStateEvent) => {
      if (value.url) {
        this.selectedIndex = (+value.url.substr(1) - 1) || 0;
      }
    });
  }
}
<mat-tab-group [selectedIndex]="selectedIndex">
...

Hope that helps.



来源:https://stackoverflow.com/questions/54326739/redirect-in-a-specified-tab-in-another-page-from-link-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!