Angular 2 - How to route to a new page without showing the html in app.component.html in the new page

Viewed 2644

I just have a general question. I know how to route between pages, but app.component.html is always shown on the top of the page every single time I go to a new page. I want to know how to stop showing app.component.html on a couple of pages. I'm creating kind of a restaurant web page as a project and I want the navigation bar to show on most pages, but some pages don't require it. I'm currently using app.routing.ts to import the components and const appRoutes: Routes = [] to set the path of the pages. If possible, I'd like a typescript answer but I can try and understand javascript

2 Answers

Let's consider two components home and login which has two different layouts, in that case, create two components using the command ng g c layouts/home-layout -s -t and ng g c layouts/login-layout -s -t which creates a two components (-t inline template -s inline style). Once this is done in app.component.html keep only router-outlet. Then in home-layout.component.ts in the template section design your layout

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home-layout',
  template: `
  <app-headding></app-headding>
  <div class="col-md-4">
    <app-menu></app-menu>
  </div>
  <div class="col-md-8">
    <router-outlet></router-outlet>
  </div>
  <app-footer></app-footer>
  `,
  styles: []
})
export class HomeLayoutComponent implements OnInit {
constructor() { }
ngOnInit() {
  }
}

similarly, create login layout without menu selector

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-login-layout',
  template: `
  <app-headding></app-headding>
  <div class="col-md-12">
      <router-outlet></router-outlet>
  </div>
  <app-footer></app-footer>
  `,
  styles: []
})
export class LoginLayoutComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

Now set up the routing module by creating child components to these modules

import { LoginLayoutComponent } from './layouts/login-layout/login-layout.component';
import { HomeLayoutComponent } from './layouts/home-layout/home-layout.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [
  {path: '', redirectTo: 'create-repo', pathMatch: 'full'},
  {path: '', component: HomeLayoutComponent,
    children: [
      {path: 'home', component: HomeComponent }
    ]
  },
  {path: '', component: LoginLayoutComponent,
    children: [
        {path: 'login', component: LoginComponent }
    ]
  },
  {path: '**', component: CreateRepoComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I hope it helps someone.

Related