英文:
PrimeNG: how to call accordion header name & collapse it from angular component.ts
问题
我想在component.ts中调用手风琴标签头的名称,以便根据某些条件折叠它。我想在ngOnInit中添加该功能。
我尝试从PrimeNG的API文档中调用某些方法,但没有成功。
<p-accordion>
<p-accordionTab header="标题 1">
内容 1
</p-accordionTab>
<p-accordionTab header="标题 2">
内容 2
</p-accordionTab>
<p-accordionTab header="标题 3">
内容 3
</p-accordionTab>
</p-accordion>
英文:
I want to call accordion tab header's name in component.ts to collapse it by some condition. i want to add that function ngOnInit.
I've tried call some method from API documentation from PrimeNG but it's not working.
<p-accordion>
<p-accordionTab header="Header 1">
Content 1
</p-accordionTab>
<p-accordionTab header="Header 2">
Content 2
</p-accordionTab>
<p-accordionTab header="Header 3">
Content 3
</p-accordionTab>
</p-accordion>
答案1
得分: 1
如果您想要在PrimeNG的p-accordion组件中更改所选的选项卡或动态切换选项卡,可以按照以下步骤进行操作:
1- 在您的HTML模板中,向p-accordion组件添加一个模板引用#accordion:
<p-accordion #accordion>
<p-accordionTab header="Header 1">
内容 1
</p-accordionTab>
<p-accordionTab header="Header 2">
内容 2
</p-accordionTab>
<p-accordionTab header="Header 3">
内容 3
</p-accordionTab>
</p-accordion>
2- 在您的组件类中,实现AfterViewInit生命周期钩子:
3- 为#accordion
模板引用添加@ViewChild
:
@ViewChild('accordion') accordion: Accordion;
4- 在ngAfterViewInit()
方法中,您可以评估您的条件并将所需选项卡的selected属性设置为true。将this.condition
替换为您的实际条件,将indexOfTab
替换为您要选择或切换的选项卡的索引。
ngAfterViewInit(): void {
if (this.condition) {
this.accordion.tabs[indexOfTab].selected = true;
// 或者
this.accordion.tabs[indexOfTab].toggle(indexOfTab);
}
}
英文:
If you want to change the selected tab or toggle the tab dynamically in PrimeNG's p-accordion component, you can follow these steps:
1- Add a template reference #accordion to the p-accordion component in your HTML template:
<p-accordion #accordion>
<p-accordionTab header="Header 1">
Content 1
</p-accordionTab>
<p-accordionTab header="Header 2">
Content 2
</p-accordionTab>
<p-accordionTab header="Header 3">
Content 3
</p-accordionTab>
</p-accordion>
2- In your component class, implement the AfterViewInit lifecycle hook:
3- Add @ViewChild
for #accordion
template ref:
@ViewChild('accordion') accordion: Accordion;
4- Inside the ngAfterViewInit()
method, you can evaluate your condition and set the selected property of the desired tab to true. Replace this.condition
with your actual condition, and indexOfTab
with the index of the tab you want to select or toggle.
ngAfterViewInit(): void {
if (this.condition) {
this.accordion.tabs[indexOfTab].selected = true;
//OR
this.accordion.tabs[indexOfTab].toggle(indexOfTab);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论