要解决这个问题,可以使用Angular的ViewChild装饰器和setTimeout函数来手动设置表单的聚焦。下面是一个示例代码:
html模板:
组件代码:
import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { TabView } from 'primeng/tabview';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('tabView') tabView: TabView;
ngAfterViewInit() {
setTimeout(() => {
const activeTabIndex = this.tabView?.findSelectedTab()?.index;
const activeTabContent = document.querySelector(`#tabpanel-${activeTabIndex}`);
const formInputs = activeTabContent?.querySelectorAll('input');
if (formInputs && formInputs.length > 0) {
const firstInput = formInputs[0] as HTMLInputElement;
firstInput.focus();
}
}, 0);
}
}
在这个示例中,我们使用ViewChild装饰器来获取对话框中的TabView组件的引用。然后,我们在组件的ngAfterViewInit生命周期钩子中使用setTimeout函数来等待DOM元素的渲染完成。
一旦渲染完成,我们获取当前选中的选项卡的索引,然后根据索引获取该选项卡的内容元素。接下来,我们使用querySelectorAll函数获取该选项卡中的所有输入元素,并将第一个输入元素设为焦点。
注意:这里使用setTimeout函数的目的是确保在Angular渲染完成之后再执行设置聚焦的操作,以避免出现错误。