Changing Page view in a SPA on angular with a button

471 views Asked by At

I'm following this link (https://coursetro.com/posts/code/29/Working-with-Angular-2-Material) to create a header on my website using Angular Material, that provides ready-to-use buttons inside the md-tab-group.

For instance, my head-component html is like this:

<md-tab-group>
    <md-tab label="1">
        <app-1></app-1>
    </md-tab>
    <md-tab label="2">
        <app-2></app-2>
    </md-tab>
</md-tab-group>

Now I can switch between page 1 and page 2 in the same URL.

The problem is that besides that way to navigate between those pages with the same URL, I want to add a button in the body of both pages that has the same functionality.

Because of that particularity, I couldn't use the <a href> or the <a routerLink> because it requires to change the URL.

Because of that, I'm struggling to add a button that does exaclty the same thing as when I click in the md-tab-group words in my header.

If someone knows how to proceed, thank you in advance!

1

There are 1 answers

0
Nehal On

Since you are using tabs, you can use the selectedIndex property provided with md-tab-group. Add a click event to the button in the body, pass the tab index to a function that sets the active tab of selectedIndex.

Here's an example:

html:

<md-tab-group [selectedIndex]="tabIndex">
  <md-tab *ngFor="let tab of tabs; let i=index">
    <ng-template md-tab-label>
      {{ tab.label }}
    </ng-template>
    <h1>{{ tab.body }}</h1>
    <div *ngFor="let x of [1, 2, 3, 4, 5]">
      <button *ngIf="x != i+1" md-raised-button color="warn" (click)="selectedTab(x)">
        <span>Go To Tab {{x}}</span>
      </button>
    </div>
  </md-tab>
</md-tab-group>

ts:

  tabIndex: number = 2;

  tabs = [
    { label: 'Tab 1', body: 'Tab 1 Body' },
    { label: 'Tab 2', body: 'Tab 2 Body' },
    { label: 'Tab 3', body: 'Tab 3 Body' },
    { label: 'Tab 4', body: 'Tab 4 Body' },
    { label: 'Tab 5', body: 'Tab 5 Body' }
  ];

  selectedTab(index){
    this.tabIndex = index - 1;
  }

Plunker demo