Enable lazy loading to retrieve the current routed module

I'm currently working on a way to exclude a component when a specific module is routed in a lazy loading application.

For instance, in my AppComponent I have a router-outlet and a component above it:

<div>
    <my-component></my-component>   --> don't show if module is StartModule
    <router-outlet></router-outlet>
</div>

This is how my routing configuration is set up:

export const routes: Routes = [
  {
    path: 'start',
    loadChildren: './start/start.module#StartModule',
  },
  {
    path: 'first',
    loadChildren: './first/first.module#FirstModule'
  },
  {
    path: 'second',
    loadChildren: './second/second.module#SecondModule'
  }
];

Is there a way to retrieve the routed module so that I can perform a check like this:

isStartModule(): boolean {
    if (routedModule == StartModule) {
        return true; 
    }
}

<my-component *ngIf="!isStartModule()"></my-component>

?

Answer №1

constructor(private router: Router ) {}

Check if the current URL is '/start' and then take some action.


  1. You have the option to subscribe to events:

     this.router.events.pipe(
        filter((event) => event instanceof NavigationEnd))
        .subscribe(x => {
            console.log('THIS IS FOR TEST', x['url']);
            }
        );
    

Answer №2

To add a route change listener in your app-component, follow these steps:

import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

constructor(private router: Router)
{
  router.events.pipe(
  filter(event => event instanceof NavigationEnd) ).subscribe((event: NavigationEnd) => {    
    console.log(event.url);
    if(event.url == 'start'){
    // run specific code
    }
});}

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

The jquery ui slider in Angular is not triggering the function when changes are made to the slider

I'm currently using Angular with jQuery UI slider and I have successfully initialized the slider and it is functioning properly. However, when I try to call another function from the change event, I encounter an error message: TypeError: this.getSe ...

How can I utilize a variable to define the key for the template HTML property in Angular 7?

Is there a method in Angular 7+ that allows me to incorporate a variable as the template html property key? I am trying to achieve something like the following: <path [attr.data-**<use-variable-here>**]="edge.id"></path> ...

When a module with routes is imported into another module with lazy-loading, the routing system becomes disrupted

Within our angular application running version 4.3.6, we have implemented lazy-loaded modules such as Fleet, Maintenance, and Car. Examining our primary app router structure: const routes: Routes = [ { path: '', redirectTo: 'fleet', ...

The binding properties of ngIf and hidden do not work properly when the condition is passed from typescript

My goal is to create a dynamic form by parsing a JSON file and binding hidden/ngIf based on a condition. I am passing the condition from the typescript file and using it in the HTML file as well. Here are the changes in my code: product.component.ts expo ...

Specify the correct type for the SVG component when passing it as a prop

Currently, I am in the process of constructing a button component: interface ButtonProps { startIcon?: ... <-- what should be the data type here? } const Button = ({startIcon: StartIcon}) => { return <button>{StartIcon && <Sta ...

Learn the process of presenting data in an HTML file using TypeScript within AngularJS 8

I recently made a GET method API call in my app.component.ts file: export class UsersComponent implements OnInit { usersdatainfo : any; constructor( private http: HttpClient ) { this.http.get(this.url).subscribe( userdata => { ...

Looking to verify the functionality of the router.navigate method when employing relativeTo?

How can we effectively test the router.navigate method to ensure it accepts provided queryParams and navigates to the correct location path? In Component file:-- syncQueryParams() { this.router.navigate([], { relativeTo: this.activatedRoute, ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

The call to 'setRequestHeader' on 'XMLHttpRequest' was unsuccessful due to the object's state not being OPENED

While developing an angular application with a restful API get(), I encountered a few errors such as unauthorization error:401 which I managed to resolve. However, now I am facing another error that seems quite straightforward. I even tried adding the CORS ...

When you use map to transform the value, Observable will consistently return as undefined

Can anyone help me figure out why, when I transform the observable, it returns undefined in the console log even though there are assigned values? HTTP Request getLibraryCardPeople(bookName: String): Observable<people[]> { return this.http.get<Li ...

What are the reasons behind the inability to implement an Angular custom pipe in a component?

Lately, my focus has been on creating an e-commerce application using Angular 14. One of the key features I am working on is the ability to filter products by brand. To achieve this, I have developed a custom pipe called app/pipes/filter-products.pipe.ts: ...

Implementing a 12-month display using material-ui components

Just starting out with ReactJs, TypeScript, and material-ui. Looking to display something similar to this design: https://i.stack.imgur.com/zIgUH.png Wondering if it's achievable with material-ui. If not, any suggestions for alternatives? Appreciate ...

Unable to display Google Places place_id when submitting a form in Angular/Ionic

Currently, I'm utilizing Google places autocomplete to fetch an array of places in the Ion-Searchbar. The form submission works smoothly, except for the input of the autocomplete field, which ideally should be the place_id instead of the actual input ...

Connecting to Asp.Net Core 6 Signal-R Takes an Unusually Long Time of 4 Minutes

I recently launched a new Asp.Net Core .Net 6 project, integrating a SignalR hub with an Angular 13 client. Although the connection eventually establishes, there is a frustrating delay of 4 minutes before it does. It's worth noting that the applicati ...

Navigating with Angular: How to pass route parameters within the same component?

Issue: There seems to be a problem with the link selection as both are getting selected when I click on one. However, the individual links display correctly. https://i.stack.imgur.com/gZWqD.png I believe that clicking on a link doesn't refresh the e ...

Leveraging the power of TypeScript and Firebase with async/await for executing multiple

Currently, I am reading through user records in a file line by line. Each line represents a user record that I create if it doesn't already exist. It's possible for the same user record to be spread across multiple lines, so when I detect that it ...

Generating form groups programmaticallyORDynamically

I recently utilized angular-archwizard to implement a wizard step with *ngFor However, I encountered an issue on how to create a dynamic formGroup for each step. In the code below, I managed to create a single formGroup for all steps, but my goal is to ha ...

Using TypeScript, let's take a closer look at an example of Angular

I am trying to replicate the chips example found at this link (https://material.angularjs.org/latest/#/demo/material.components.chips) using TypeScript. I have just started learning TypeScript this week and I am having some difficulties translating this co ...

The array within the JSON object holds vital information [Typescript]

I have some data stored in an Excel file that I want to import into my database. The first step was exporting the file as a CSV and then parsing it into a JSON object. fname,lname,phone Terry,Doe,[123456789] Jane,Doe,[123456788, 123456787] Upon convertin ...