Angular How to catch mat-tab changed event
You can do it in this way
<mat-tab-group [(selectedIndex)]="selectedTabIndex" (selectedTabChange)="onTabChanged($event);">
<mat-tab formArrayName="staffMembers" #pft *ngFor="let staffMember of formData.get('staffMembers').controls; let i = index">
<div [formGroupName]="i">
<ng-template mat-tab-label>
{{staffMember.controls.staffMemberId.value}} <a>
</a>
</ng-template>
<div class="form-group">
<label for="name"> Name</label>
<input type="text" class="form-control" id="name" formControlName="name">
</div>
</div>
</mat-tab>
</mat-tab-group>
and Create FormArray For staffMember Like this in Component
formData: FormGroup = this.formBuilder.group({
staffMembers: this.formBuilder.array([this.createItem()])
}
On Tab Change you can assign value To form Array
createItem(): FormGroup {
return this.formBuilder.group({
staffMemberId: ['',],
name: ['',],
});
}
addItem(): void {
this.projectFundingItems = this.formProjectGeneralData.get('staffMembers') as FormArray;
this.projectFundingItems.push(this.createItem());
}
onTabChanged($event) {
let clickedIndex = $event.index;
let length = (<FormArray>this.formData.controls['staffMembers']).length;
if (clickedIndex === length) {
if ((<FormArray>this.formData.controls['staffMembers']).at(length - 1).dirty) {
this.addItem();
this.selectedTabIndex = clickedIndex - 1;
} else {
if (this.formData.staffMembers.length === clickedIndex) {
this.addItem();
}
this.selectedTabIndex = clickedIndex - 1;
}
}
}
It starts from index 0 to the number of tabs you create.
In your html
<mat-tab-group #tabGroup (selectedTabChange)="tabChanged($event)">
<mat-tab label="Tab 1">Content 1</mat-tab>
<mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>
In component use this code
tabChanged = (tabChangeEvent: MatTabChangeEvent): void => {
console.log('tabChangeEvent => ', tabChangeEvent);
console.log('index => ', tabChangeEvent.index);
}
this should be fine as you need.