【问题标题】:How can attach a route to the display of an ng-accordion panel?如何将路线附加到 ng-accordion 面板的显示?
【发布时间】:2017-11-16 00:09:30
【问题描述】:

我有一个使用 *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>

映射的路线可能是:

/faq/ABCD
/faq/EFGH
/faq/IJKL

切换特定面板将更新位置/ActiveRoute,并粘贴将映射到特定面板的 URL 将导致该面板展开。关于如何连接它有什么建议吗?

【问题讨论】:

    标签: angular ng-bootstrap angular-component-router


    【解决方案1】:

    您的应用程序路由需要像这样配置,我们需要 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。

    【讨论】:

    • 太棒了,谢谢!这看起来几乎完美无缺。是否有其他已定义事件的文档,或者我只需要了解源代码?
    • 很高兴它对你有用。有一些简单的文档here。我使用它和他们的GitHub 来确定要使用的事件和属性。
    猜你喜欢
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    相关资源
    最近更新 更多