Home > Back-end >  How to switch Tab and pass Data
How to switch Tab and pass Data

Time:10-01

My Component structure

customer - material tab

  • contains Tab1 - customer table view
  • contains Tab2 - edit customer view
<mat-tab-group>
  <mat-tab label="View">
    <div>
      <app-customer-table></app-customer-table>
    </div>
  </mat-tab>
  <mat-tab label="Edit">
    <div>
      <app-customer-create></app-customer-create>
    </div>
  </mat-tab>
</mat-tab-group>


When I click on an "edit" icon, that is inside Tab1, I want to switch to Tab2 and pass my "customer:CustomerDTO" to it.

How can I achieve this?

CodePudding user response:

You can achieve that in a few steps:

  1. Create a service using this command:
ng generate service data-passing
  1. Define two variables in that service that holds your data for each component:
import {Injectable} from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class DataPassingService {
  public firstTabData;
  public secondTabData;

  constructor() { }

}
  1. Use service in your component:
import {DataPassingService} from '...';

...
constructor(public dataPassingService: DataPassingService) {
}
  1. Store each component data in relative variable:
setDate(first, second) {
  this.dataPassingService.firstTabData = first;
  this.dataPassingService.secondTabData = second;
}
  1. Use each data you want in tabs

you can also define a data variable and store data there instead of two variables

CodePudding user response:

To pass data to the component, you can either use a service or use property binding and event binding syntaxes like this:

Inside tab1, use an EventEmitter. Once the user clicks edit invoke the emit function and pass the required data.
Using event binding, retrieve the data in the parent component and pass it to the child component by property binding.

Check here: https://fireship.io/lessons/sharing-data-between-angular-components-four-methods/

To switch tab, inject the <mat-tab-group> in component.ts using @ViewChild decorator and change the selectedIndex property of it.

CodePudding user response:

You can use @Output in the first component --> store value in a variable You can use @Input in the second component and pass the above variable

Code looks like below:

 <mat-tab-group>
  <mat-tab label="View">
    <div>
      <app-customer-table (onClickEdit)="edit($event)"></app-customer-table>
    </div>
  </mat-tab>
  <mat-tab label="Edit">
    <div>
      <app-customer-create [customerId]="customerId"></app-customer-create>
    </div>
  </mat-tab>
</mat-tab-group>

// main-componet.ts file

edit(value)=>{
this.customerId = value;
}

// customer-create.component.ts

@Input CustomerId;

// customer-table.component.ts
@Output onClickEdit = new EventEmitter<string>();
  • Related