从链接Angular 6重定向另一个页面的指定选项卡中

时间:2019-01-23 11:56:31

标签: angular angular-material

我正在使用Angular 6.2和Angular材质。

我的页面上有Mat标签(3个标签)。

是否可以在此页面中重定向,但第3个标签处于活动状态?通过单击导航栏中的链接。

似乎不可能,网站上对此没有任何解决方案。

3 个答案:

答案 0 :(得分:2)

如果使用的是mat-tab-group,则有一个input属性可以指定活动选项卡的索引。

@Input() selectedIndex:数字| null =>活动标签的索引。

请参阅Official docs for mat tab groups

答案 1 :(得分:0)

这是使用 Location 服务的解决方案,该服务不使用Angular Router,而是侦听路由中的哈希片段,并为其设置 selectedIndex ,这样,标签页的内容都会全部加载到同一页面中,但是activeTab将与路由中设置的片段匹配。

用于转到页面并激活标签的链接为/my-page#0/my-page#1 ...

这是 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">
...

希望有帮助。

答案 2 :(得分:0)

我找到了一个好的解决方案:

我使用queryParams

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

然后,如果有选项卡且其值为=通知,则我将我的选项卡设置为活动状态

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

在控制器中,如果有queryparams,则设置选项卡(this.tab)并将其删除,因此我从未看到

  

?tab =通知

在我的网址中。

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