Reputation: 96
I have a mat-tab-group in a component called "person". In a parent component called "persons", I have two identical person components, and each of them has 3 tabs in its mat-tab-group. I want the components to be synchronized with their selected tab. For example, when I switch for tab 1 to tab 2 in one person, the second person should also do that.
I tried using @Input and @Output to communicate between the parent component and its children, but that didn't work. I also tried using a service to hold the currently selected tab, but I'm missing something because the components still do not sync.
That's the parent component:
<app-person-source [person]="persons[0]"></app-person-source>
<app-person-source [person]="persons[1]"></app-person-source>
And that's the child component:
<mat-tab-group class="demo-tab-group">
<mat-tab>
<person-details-tab></person-details-tab>
</mat-tab>
<mat-tab>
<person-identifiers-tab></person-identifiers-tab>
</mat-tab>
<mat-tab>
<person-merged-persons-tab></person-merged-persons-tab>
</mat-tab>
</mat-tab-group>
Upvotes: 2
Views: 2677
Reputation: 96
I made it work using ngrx store
, with 3 actions and effects. Code is pretty similar to:
https://www.logisticinfotech.com/blog/easiest-demo-to-learn-ngrx-in-angular-6/
Upvotes: 0
Reputation: 56
As you stated, you can create a shared service to sync data between components. Service code should be as follows:
@Injectable({
providedIn: 'root'
})
export class SharedService {
private tabIndexChanged$: BehaviorSubject<number> = new BehaviorSubject<number>(0);
get tabIndexChanged(): Observable<number> {
return this.tabIndexChanged$.asObservable();
}
tabChanged(tabIndex: number): void {
this.tabIndexChanged$.next(tabIndex);
}
}
After injecting this service in your child components, you need to subscribe to the service in the children:
this.sharedService.tabIndexChanged.subscribe(tabChanged => {
// logic after tab changed should be here
})
Upvotes: 1