您的应用程序路由需要像这样配置,我们需要 faqId 作为路由的参数:
export const appRoutes = [
{
path: 'faq/:faqId',
component: FaqComponent
}
];
并像这样导入到您的模块中:
imports: [RouterModule.forRoot(appRoutes)]
在标记中:
<ngb-accordion closeOthers="true" [activeIds]="selectedFaqId" (panelChange)="onPanelChange($event)">
<ngb-panel *ngFor="let faq of faqs" id="{{faq.id}}" title="{{faq.title}}" >
<ng-template ngbPanelContent>
{{faq.body}}
</ng-template>
</ngb-panel>
</ngb-accordion>
组件(我为这个例子模拟了数据):
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbPanelChangeEvent } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-faq',
templateUrl: './faq.component.html'
})
export class FaqComponent {
selectedFaqId = '';
faqs = [
{
id: 'a',
title: 'faq 1 title',
body: 'faq 1 body'
},
{
id: 'b',
title: 'faq 2 title',
body: 'faq 2 body'
}
];
constructor(private route: ActivatedRoute, private router: Router) {
route.params.subscribe(x => {
this.selectedFaqId = x.faqId;
console.log(this.selectedFaqId);
})
}
onPanelChange(event: NgbPanelChangeEvent) {
this.router.navigateByUrl(`faq/${event.panelId}`);
console.log(event);
}
}
我添加了对路由参数的订阅,以便我们可以在路由更改时重置 selectedFaqId。
我将 selectedFaqId 绑定到手风琴的 selectedIds 属性。这将展开所选 ID 的面板。
我通过绑定到 panelChange 事件来响应手风琴面板的手动扩展。在那种情况下,我们将路由设置为所选的 Faq Id。这会将 url 导航到 selectedFaqId。