使用@ViewChild和ngAfterViewInit生命周期钩子来解决此问题。在组件的类定义中,定义一个ViewChild以获取与选项卡关联的元素,并在ngAfterViewInit生命周期钩子中订阅选项卡更改事件,更新FormGroupName。
示例代码:
HTML:
TypeScript:
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { MatTabGroup } from '@angular/material/tabs';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-tabs',
templateUrl: './tabs.component.html',
styleUrls: ['./tabs.component.css']
})
export class TabsComponent implements AfterViewInit {
@ViewChild(MatTabGroup) matTabGroup: MatTabGroup;
form: FormGroup;
selectedTabIndex: number = 0;
constructor(private fb: FormBuilder) {
this.form = fb.group({
tab1: fb.group({
...
}),
tab2: fb.group({
...
})
});
}
ngAfterViewInit() {
this.matTabGroup._tabs.forEach((tab, index) => {
tab.onClick.subscribe(() => {
this.selectedTabIndex = index;
this.form.controls['tab1'].updateValueAndValidity({ emitEvent: false });
this.form.controls['tab2'].updateValueAndValidity({ emitEvent: false });
});
});
}
}