Differentiating Layout Routing in Angular 2

In my unique Angular 2 application, I am facing a challenge with the layout. The home page has a completely different layout compared to the rest of the app, which only share a navigation bar.

Here are some sample URLs:

http://localhost:4200/ <== home page layout

http://localhost:4200/cgu <== common nav page

http://localhost:4200/abc <== common nav page

Seeking guidance on the best approach to handle this issue, I attempted to implement a solution found on Stack Overflow :

How to switch layouts in Angular2

However, the solution did not work for me or maybe I made an error while adapting it to my scenario.

EDIT:

After trying various solutions, I decided to create a navigation service named navigation.service.ts

@Injectable()
export class NavigationService {
  isHomePage: boolean;
}

In my home component file (home.component.ts):

@Component({
  styleUrls: ['home.css'],
  templateUrl: './home.component.html',
})
export class HomeComponent {

  constructor(private navigationService: NavigationService) {
    navigationService.isHomePage = true;
  }
}

Within my app component file (app.component.ts), I attempted to access the value of isHomePage:

export class AppComponent {

  constructor(private navigationService : NavigationService) {

    console.log("HELLO");
    console.log(navigationService.isHomePage);
    if(navigationService.isHomePage)
      console.log("HOME");
}}

The output shows that navigationService.isHomePage is currently undefined. Any idea what might be causing this issue?

Answer №1

I suggest taking a look at the official documentation for a clear understanding supported with examples.

The Angular Router facilitates seamless navigation between different views as users interact with the application.

To ensure that the correct template is displayed when navigating to a specific route, you need to bind a component to it.

If you want to have a common navigation structure across multiple views, place it outside the router-outlet. This way, the content of each view will be loaded within the outlet while keeping the navigation separate.

__

If you prefer not to show the navigation on your homepage, you can implement the following approach:

Create a NavigationService containing a boolean variable named isHomepage. Set this variable to false when leaving the homepage and true when returning to it. Then, inject this service into your navigation component and use the following code snippet in your template:

<nav *ngIf="!_navigationService.isHomePage"></nav>

This method ensures that the navigation menu is only displayed outside the homepage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for implementing a guard feature using a modal window

I am looking to implement a dialog window with yes and no responses when clicking on a router link. If the user selects 'yes', I want to pass through the canActivate guard. The issue arises when returning to the same router with the guard in pla ...

Attempting to start an Angular project using NG NEW constantly fails nowadays - always ends with error code EPERM

Can Angular still be considered a reliable framework when pervasive errors and bugs persist for extended periods without any clear resolution documented? .... 24695 silly saveTree | +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

What could be the reason for Angular 2 not recognizing this valid regex pattern?

The regular expression shown below is considered valid (check here): ^(\+27|27|0)\s?(\d{2})[-\s]?(\d{3})[-\s]?(\d{4})$ Despite its validity, Angular 2 throws the following error: EXCEPTION: Error in ./App class App - i ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

The crosshair functionality in Zing Chart is causing a CPU leak

After enabling the crosshair feature on my chart, I noticed a significant issue when using Chrome 57 (and even with versions 58 and ZingChart 2.6.0). The CPU usage spikes above 25% when hovering over the chart to activate the crosshair. With two charts, th ...

Having difficulty installing node-sass in an Angular project

Having downloaded a repository from an existing Angular project, I proceeded to run sudo npm install within the project. While all packages were successfully installed, the node-sass package continued to cause issues. Upon completion of the installation ...

Executing ng test and ng serve at the same time

As someone who is still learning Angular 5, I am in the process of setting up a development environment for my team to work on a new Angular 5 application. My goal is to have our team able to run linting tests and unit tests every time they make changes, ...

Utilizing electron as a development dependency in an Ubuntu environment

After installing electron on Ubuntu 17.10, this is the process I followed: ole@mki:~/angular-electron$ npm i --save-dev electron > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9bcb5bcbaadabb6b799e8f7eef7e8eb"> ...

Unable to access setRowData() in AgGrid/Angular 2 leads to rendering of the grid without displaying any rowData

Resolved I think my solution is temporarily fixed and it reveals that I may have set up my mongoose model incorrectly. The answer provided did assist me in solving my issue, but ultimately the reason for the empty data rows was due to incorrect identifier ...

Is it considered poor coding practice to utilize the store.dispatch method within an effect in an Angular NgRx application?

This particular question is an extension of a post that can be found here. However, I believe my query is more focused and specific, so I feel it's worth pursuing an independent answer rather than relying solely on the linked post. Context In the af ...

Error: NativeScript has encountered difficulty locating the module "@nativescript/schematics"

While attempting to generate a component called "movies" with the command tns generate component movies, I encountered the following error in the terminal log: Could not find module "@nativescript/schematics". I followed the suggestions provided in this G ...

Capturing a webpage through Record RTC integration with Angular

I am looking to record a specific section of the page as a video with audio. For example, when a user enters the page, I want it to automatically start recording the activities in that particular area (similar to how iframe videos work). The recording sh ...

How to toggle tooltip visibility dynamically using Angular 2

I am working with elements within an ngFor loop. Some of these elements have tooltips, while others do not. I am experiencing an issue where when using the code snippet below: <div ngFor="let item of items"> <div [title]="item.title"> Ele ...

When null is assigned to a type in Typescript, it does not result in an error being triggered

Could someone enlighten me on why this code is not causing an error? import { Injectable } from '@angular/core'; interface Animal{ name: string; } @Injectable() export class AnimalService { lion: Animal = null; constructor() {} get(){ ...

Creating a release of an Angular 12 library using Ivy and sharing it on npm

Recently, I had the task of updating a library to angular 12. After successfully compiling it with Ivy full compilation mode, I realized that it cannot be published on npm in this state. Following suggestions from various sources, I tried setting "enableI ...

Ways to activate Form Validators in angular2?

I recently developed an Angular2 web application and successfully integrated a custom validator using the form builder. Although it works when the form is submitted, I am facing difficulties in triggering validation dynamically based on changes in other fo ...

Resolving the Angular NG0100 Error: Troubleshooting the ExpressionChangedAfterItHasBeenCheckedError

I am currently working on implementing a dialog component that takes in data through its constructor and then utilizes a role-based system to determine which parts of the component should be displayed. The component code snippet looks like this: export cl ...

The footers on each page are not consistent

I have noticed that two pages utilizing the same CSS are displaying differently. Check them out here: 128.48.204.195:3000 128.48.204.195:3000/formats If you look closely, you'll see that below the footer, the /formats page appears to have no extra s ...

Using JavaScript to dynamically calculate the sum of selected column values in Angular Datatables

I have a table set up where, if a checkbox is checked, the amounts are automatically summed and displayed at the top. However, I am encountering issues with the code below as it is not providing the exact sum values. Can anyone suggest a solution to this p ...

Is it conceivable that Rails may be rendering HTML at a slower rate compared to static

When using a Rails layout, you can include HTML tags to render images like this: <%= image_tag("logo.png", :alt => "Sample App", :class => "round") %> This will generate the following HTML code: <img alt="Sample App" class="round" src="/i ...