ashish
ashish

Reputation: 21

when lazy loading mat-tab content using <router-outlet>, within mat-tab content routed component is initialized ( constructor and Init) twice

I have created a mat tab group and using ng-for to load tabs using router outlet, As I add new tab and navigate the url my new routed component is constructed twice and previous tab content is replaced with new content.

Sample Code:
mat-tab-group (selectedTabChange)="tabClick($event)" [selectedIndex]="selected.value"
  (selectedIndexChange)="onIndexChanged($event)" animationDuration="0ms">
   <mat-tab *ngFor="let tab of tabs; let i = index" [label]="tab">
    <ng-template mat-tab-label>     
      {{tab.Name}}
    </ng-template>        
   <router-outlet></router-outlet>           
  </mat-tab>
</mat-tab-group>

typescrpt code :

export class MyTabComponent implements OnInit { public tabs: any; // property which I loop in HTML public selected = new FormControl();

 ngOnInit() {
 this.myservice.NewTabArrived.subscribe(
  (newTab) => {

   let url = newTab.Url   // URL of comp to load in new tab
   this.tabs.push({tabName:newTab.Name}); // This is use din ngFor in html

   this.router.navigate([url], {relativeTo: this.activatedRoute });
 }); 

The problem is when first time subscribe function called it loads route successfully under tab. For next time when its called, component for specified url is constructed twice and previous tab content shows new tab content (previous tab content is lost).

When first time subscribe is called ----- Tab1 (selected) | ------ Tab1 Content

When second time subscribe is called

Tab1 | Tab2(selected) |

Tab2 Content

When i click tab1 I see tab2 content (the problem i'm facing)


Tab1(selected) | Tab2

Tab2 Content


Can someone help please, why on adding second tab my previous tab content is also loaded with second component.

Thanks in advance.

Upvotes: 2

Views: 646

Answers (1)

Amit
Amit

Reputation: 1491

Try wrapping router-outlet inside #matTabContent

<mat-tab-group><mat-tab *ngFor="let tab of tabConfig">
                            <ng-template mat-tab-label >
                                {{tab.label}}
                            </ng-template>
                            <ng-template matTabContent>
                                <router-outlet></router-outlet>
                            </ng-template>
                        </mat-tab>
                    </mat-tab-group>

Upvotes: 0

Related Questions