如何将路线附加到ng-accordion面板的显示屏上?

Dev*_*ips 2 angular-component-router ng-bootstrap angular

我有一个使用*ngFor循环定义的ng-accordion ,我想调整位置并将路径绑定到特定面板的视图.理想情况下,当客户端单击以展开面板时,该位置将在浏览器中更新,并且新的历史记录项将存储在浏览器中.此外,如果客户输入的URL对应于正在显示的特定手风琴项目,我希望确保反映出适当的状态.

例如:

<ngb-accordion closeOthers="true">
  <ngb-panel *ngFor="let faq of faqService.getItems()" id="{{faq.id}}" title="{{faq.title}}">
    <ng-template ngbPanelContent>
      {{faq.body}}
    </ng-template>
  </ngb-panel>
</ngb-accordion>
Run Code Online (Sandbox Code Playgroud)

映射的路由可能是:

/faq/ABCD
/faq/EFGH
/faq/IJKL
Run Code Online (Sandbox Code Playgroud)

切换特定面板将更新位置/ ActiveRoute并粘贴将映射到特定面板的URL将导致该面板被展开.关于如何连线的任何建议?

Joe*_*man 5

你的应用程序路由需要像这样配置,我们需要faqId作为路由的参数:

export const appRoutes = [
  {
    path: 'faq/:faqId',
    component: FaqComponent
  }
];
Run Code Online (Sandbox Code Playgroud)

并导入到您的模块中,如下所示:

imports: [RouterModule.forRoot(appRoutes)]
Run Code Online (Sandbox Code Playgroud)

在标记中:

<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>
Run Code Online (Sandbox Code Playgroud)

组件(我为此示例模拟了数据):

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

我添加了对路由参数的订阅,以便我们可以在路由更改时重置selectedFaqId.

我将selectedFaqId绑定到手风琴的selectedIds属性.这将展开所选Id的面板.

我通过绑定panelChange事件来响应手风琴面板的手动扩展.在那种情况下,我们将路线设置为选定的Faq Id.这将导航url到selectedFaqId.