【问题标题】:Angular 9 use two different layouts in the same applicationAngular 9 在同一个应用程序中使用两种不同的布局
【发布时间】:2020-10-07 18:12:35
【问题描述】:

我的应用程序包含两种不同的布局。一种布局是我们显示顶部导航和侧边栏的应用程序。

<app-nav></app-nav>
<div>
  <app-sidebar></app-sidebar>
  <router-outlet></router-outlet>
</div>

第二个布局是登录和注册页面,我们没有导航栏和侧边栏。

天真的解决方案是基于当前路由将ngIf 添加到两个元素。但我更喜欢避免它。原因是我们在这些组件中有我们不想在不需要的地方加载的代码。

有没有更好的办法解决这个问题?

【问题讨论】:

    标签: javascript angular router


    【解决方案1】:

    让 AppComponent 包含一个 router-outlet 作为模板。

    @Component({
      selector: 'app-root',
      template: `<router-outlet></router-outlet>`
    })
    export class AppComponent {
      constructor() {
      }
    }
    

    然后将路线包括为:

    const routes: Routes = [
      {
        path: '',
        pathMatch: 'full',
        component: AppComponent,
        canActivate: [LanguageGuard]
      },
      {
        path: ':lang',
        component: LanguageComponent,
        children: [
          {
            path: 'partner',
            loadChildren: () => import('./partner/partner.module').then(m => m.PartnerModule)
          },
          ...ClientRoutes,
          ...AuthRoutes
        ]
      }
    ];
    

    我的项目对partnerClientRoutes/AuthRoutes 有不同的布局

    合作伙伴:

    const routes: Routes = [{
      path: '',
      component: PartnerLayoutComponent,
      children: [
        {
          path: '',
          component: HomeComponent
        },
        {
          path: 'profile',
          component: ProfileComponent
        }
      ]
    }];
    

    这是ClientRoutes/AuthRoutes的内容:

    export const ClientRoutes: Routes = [{
      path: '',
      component: ClientLayoutComponent,
      children: [
        {
          path: '',
          component: HomeComponent
        },
        {
          path: 'sofa',
          component: SofaComponent
        }
      ]
    }];
    

    然后你将我的PartnerModule 更改为你的login 模块并延迟加载它。

    但不是每个用户都需要登录吗?也许只把注册过程放在那个模块里。

    【讨论】:

      【解决方案2】:

      如果您要延迟加载模块,这很容易:

      1. 添加带有&lt;router-outlet&gt; 的第二个“布局”页面

      2. 在您的路线中,像这样定义您的路线:

        const routes:Routes=[{path:'some-path', component: YourLayoutComponent, loadChildren: ()=> import('./lazy-loaded-module/lazy-loaded.module').then(m =>m.LazyLoadedModule) }];

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-04
        • 2017-04-11
        • 2011-11-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多