如何在Angular中组织路由?

时间:2019-11-11 12:48:47

标签: angular angular6 angular8

我的组件SkeletonComponent中带有标签:

<div class="tabs">
   <div class="tab" *ngIf="showTab(1)"><app-journal></app-journal></div>
   <div class="tab" *ngIf="showTab(2)"><app-journal-extended></app-journal-extended></div>
</div>

因此,有一种机制可以按条件激活选项卡。它放置在父组件SkeletonComponent中。

现在,我想添加路由,以按路由激活特定的标签:

  { path: "skeleton", component: SkeletonComponent,  children: [
      {
    path: "journal",
    component: JournalComponent
  },
  {
    path: "journal/:id",
    component: JournalExtendedComponent
  }
  ]},

这是正确的方法吗?

1 个答案:

答案 0 :(得分:2)

如果要让路由器处理此问题,请不要使用模板中的组件。使用路由器插座。本示例使用了“材料组件”中的“选项卡”。请更改为您的用户界面详细信息。您还需要将JournalExtendedComponent的子路由路径更改为journal/details/:id

skeleton.component.html

<nav mat-tab-nav-bar>
    <button mat-tab-link *ngFor="let item of menuItems" (click)="selectTab(item)" [active]="activeTabIndex == item.id">{{item.title}}</button>
</nav>
<router-outlet></router-outlet>

skeleton.component.ts

export class JobsForTutorComponent {
  menuItems: MenuItem[] = [
    {
      id: 0,
      title: 'Tab Title 1',
      route: '/route-to-component',
    },
    {
      id: 1,
      title: 'Tab Title 2',
      route: '/route-to-other-component'
    }
  ];
  activeTabIndex: number;

  constructor(
    private router: Router,
    private route: ActivatedRoute) {
    const routedMenuItem = this.menuItems.find(menuItem => menuItem.route === this.router.url);
    if (routedMenuItem) {
      this.selectTab(routedMenuItem);
    } else {
      this.activeTabIndex = 0;
    }
  }

  selectTab(tabItem: MenuItem) {
    this.activeTabIndex = tabItem.id;
    this.router.navigate([tabItem.route]);
  }
}

menu-item.model.ts

export interface MenuItem {
    id?: number;
    title?: string;
    route?: string;
}

编辑:根据情况进行路由

{
    path: "journal",
    component: SkeletonComponent,
    children: [
      {
       path: "overview",
       component: JournalComponent
      },
      {
       path: "detail/:id",
       component: JournalExtendedComponent
      }
  ]
}
组件中的

menuItems数组将为:

menuItems: MenuItem[] = [
    {
      id: 0,
      title: 'Overview',
      route: '/overview',
    },
    {
      id: 1,
      title: 'Details',
      route: '/detail'
    }
  ];