Home > front end >  Changing component view based on route
Changing component view based on route

Time:01-01

I'm trying to show/hide an Angular component based on the route. If there's a simpler way, please let me know. I've tried many examples off stackoverflow but none seemed to work. Here is my code.

app.component.html:

<app-nav></app-nav> //shown on all pages
<app-home> </app-home> //shown only on home route ('/')
<app-contact> </app-contact> //shown only on contact route ('/')

nav.component.html:

<div  *ngIf="navStatus == 'contact'">
    <button (click)="contactPage()"> Contact </button>
</div>

nav.component.ts:

contactPage() {
    this.router.navigate(['/contact']);
 }

app-routing.module:

const routes: Routes = [
  { path: '', component: HomeComponent},
  { path: 'contact', component: ContactComponent}
];

Ideally, once I select the button from nav html, it will change the route to /contact (which it does), but I want the app.component.html to only show the <app-contact>, and not the <app-home>.

CodePudding user response:

It looks like you want to use the RouterOutlet. You've already set up the correct components for your routes:

app-routing.module.ts

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent }
];

So all you need to do is add the router-outlet placeholder to your app template:

app.component.html

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

Once you've done this, Angular will render the HomeComponent where the router-outlet is when the ActivatedRoute is / and will render the ContactComponent where the router-outlet is when the ActivatedRoute is /contact.

You set the ActivatedRoute by typing the desired route in the URL bar of your browser, using the RouterLink directive on an element in a template, or using one of the methods on the Router like you've done with this.router.navigate(['contact']).


Here's what using the RouterLink directive would look like in your navigation:

nav.component.html

<a routerLink="/contact">Contact</a>

There are more examples (including more advanced use cases) in the RouterLink documentation.

  • Related