How to use separate layout for login component in

2020-06-09 12:06发布

问题:

I am new in angular. I create a login component , it works fine fine but issue is that I want a separate layout of login from whole app. What changes required for that?

I search on google but everyone give diff solution which not understandable also.

const appRoutes: Routes = [
{ path: 'alert/:id', component: AlertDetailComponent },
{ path: 'alerts', component: AlertsComponent },
{ path: 'dashboard', component: EriskDashboardComponent },  
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },  
];

In app.component.html

<!-- page content -->
<div class="right_col" role="main">
    <router-outlet></router-outlet>           
</div>
<!-- /page content -->

回答1:

In your app.component.html:

<router-outlet></router-outlet>

Then create MainComponent (main.component.ts) and put all of your main app layout in main.component.html:

<!-- page content -->
<div class="right_col" role="main">
    <router-outlet></router-outlet>           
</div>
<!-- /page content -->

This component will be parent for each your regular app component.

Then in your LoginComponent put different layout without router-outlet, for example:

<div class="login-wrapper">
  <div class="login">
   ... your login layout
  </div>
</div>

Then modify your routing to be something like that:

const appRoutes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: '', component: MainComponent, redirectTo: '/dashboard', pathMatch: 'full',
    children: [
      { path: 'alert/:id', component: AlertDetailComponent },
      { path: 'alerts', component: AlertsComponent },
      { path: 'dashboard', component: EriskDashboardComponent }
  ]}];

So MainComponent will contain all reusable layouts and app structure for any child component, while LoginComponent is independent and it has its own layout.



回答2:

In the "most" parent component you can .subscribe to the router.events data and once you hit the login component as active route, that component will be notified and add a css class or id for the different layout(theme) you want (perhaps that would be encapsulated in a partial scss file - if you don't use scss/sass perhaps you should consider it).

Once, you change route (other than login) the class will be gone and the "custom" (different) layout will not be applied anymore.

Hope that might help. You can always use a @Output/ @Input() or a shared singleton service with observables (for non parent-child components relationship) to share state between those components and do stuff based on state change. If you have any questions/comments feel free to add them. I think angular docs can help with the implementation details.