Angular Route Check with If Statement

Can someone assist me with creating an if-statement in my program to determine the current route or path I'm on?

I have a function that should only execute when I'm on a specific path. For instance, if the path is "homepage", then I know I'm on the homepage. However, if the URL includes "homepage/add", I want to trigger a different function. I attempted to use the code:

if(this.router.url.include('add') { .... code ... }
, but it did not work as expected. Any help would be greatly appreciated! Thank you!

Answer №1

To implement a nested route '/add', you need to include it in the routes array and create a component for this route where you can call your function inside the ngOnInit() method.

const routes: Routes = [
  {
    path: 'homepage',
    component: DashboardComponent,
    children: [
      {path: 'add', component: DashboardAddComponent}
    ]
  }
]

Next, within the DashboardAddComponent class:

class DashboardAddComponent implements OnInit {
  ngOnInit() {
    // ... CALL YOUR FUNCTION HERE
  }
}

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

If placed in the same document, will promises be executed sequentially?

Let's say I have a function in one file that returns a promise: public async a():Promise<string>{ return 'hi' } In another file, I use this function like so: await service.a.then( hi =>console.log(hi)).catch(err=>{throw err}); ...

Does Vue.js have its own version of Angular's named templates feature?

Check out this snippet of Angular code: <ng-container *ngIf="someCondition; else spinner"> Show Data </ng-container> <ng-template #spinner> Show Spinner </ng-template> Do you know if there is a similar vue.js equ ...

Enhance the visual appeal of incoming data using Angular Material's dynamic styling feature

Is it possible to enhance the text with some CSS styling to make each item stand out like in this example: https://i.stack.imgur.com/kSyZE.png I prefer not to include a cross button or provide users with the option to add tags. The data is coming from a R ...

The recent update from Angular version 5.2 to 7 has caused issues with Post methods

An issue has occurred with the type mismatch in the error handling function. It seems that the argument provided is not compatible with the expected parameter type within the Observable structure. GetFullAddress(addressModel: FullAddr ...

Module 'glob' not located

Please provide any additional information needed Currently, I am working through a step-by-step guide to set up my first Angular 2 application and have encountered the following issues: npm i -g angular-cli //(successful) ng new ponyracer //(e ...

Evaluate Angular component through unit testing by employing tick and fakeAsync to handle Observables efficiently

Although I have come across similar questions multiple times, I couldn't find a precise solution. There are numerous solutions available which can be confusing for someone like me who has recently started working with Angular. Here is an example of a ...

The React lifecycle method componentDidMount is failing to execute

In my React application, I have the following route setup: <Route path={`${this.props.match.path}horoskop`} render={() => <HoroscopeController horoscopeService={this.horoscopeService} fortuneTellerService={this.fortuneTell ...

Ng2-smart-table is experiencing difficulty showing date and time values when used on Internet Explorer

In my Angular 7 application, I am utilizing ng2-smart-table. Within the table, I have incorporated the owl-datetime picker for selecting date and time values to be added to the database. The data is retrieved from the backend in an array format and then d ...

Allusion to a intricate data component

In my code, I have a model that is being represented by a class. For example, let's consider the model of a car: export class Car { public name : string; public color: string; public power : number; public service : boolean; } All c ...

Invoking a method in a child component from the parent component using Angular

In my parent component, there are three instances of a child component nested inside. child-product-detail.component.html <form id="frmProduct" #frmProduct="ngForm" (ngSubmit)="onSave(frmProduct)"> <ng-content sel ...

Uploading files in Angular 5 with additional properties of other objects

I am facing a challenge with uploading a file as part of a property to an object within a form. Most documentations I have come across only focus on services that handle standalone files. In my case, I have a form with various text inputs and date pickers, ...

How can I determine which dist folder is utilized during the building of my App if an npm package contains multiple dist folders?

I have integrated an npm package called aurelia-google-maps into my application. This package includes various distribution folders such as AMD, System, CommonJS, Native Modules, and ES2015 within the /node_modules/ directory like so: /node_modules/ /a ...

The automatic renewal of silent access tokens in Oidc client js fails due to the failure of the sliding expiration feature of the identity server authentication cookie

Working on an angular single-page application (SPA) that utilizes authentication through Identity Server 4 and OIDC client js. Encountering issues with the silent access token renew process. The expected behavior is for the access token to automatically r ...

Tips for successfully importing $lib in SvelteKit without encountering any TypeScript errors

Is there a way to import a $lib into my svelte project without encountering typescript errors in vscode? The project is building and running smoothly. import ThemeSwitch from '$lib/ThemeSwitch/ThemeSwitch.svelte'; The error message says "Canno ...

What is the reason behind the extra space generated when a keyframe content contains a diacritic mark?

My Angular app's home page features dynamic word changes defined in CSS: .header-text:after { display: inline-block; content:''; animation: fide-in 5s linear infinite; } @keyframes fide-in { 0% { content:'BLA'; opacit ...

Handling a callback after the completion of another action in Angular 2

I am facing an issue where I need to delete an item from a list and then update the page to reflect that change. The current code handles the deletion of the item using DELETE_APPLICATION and then fetches the updated list using GET_INSIGHT_APPLICATIONS. Ho ...

The issue with Multiselect arises when the array is being set up initially

Using primeng Multiselect, I have implemented a logic to push data based on search value from the backend. To avoid the error of pushing undefined elements, initialization is required before pushing. However, when I initialize the dropdown's array var ...

Unable to retrieve title from view source with Angular 5 Universal

Looking for some assistance with setting up custom headers and footers in Angular 5. I have scoured the internet and tried various examples, but haven't had any luck. Link to my question on Stack Overflow about Header and Footer in Angular 5 I' ...

A Single Codebase Supporting Websites in a Variety of Languages

I have been tasked with a project to demonstrate the concept of one codebase managing multiple websites. Any requests for these websites would first go through the main project directory, which then directs them to the specific website based on the domain ...

Utilizing CucumberJs, Protractor, and TypeScript to Implement Dynamic Tags/Variables in .feature Files

Currently, I am facing a challenge where I have multiple environments with various features enabled. My goal is to streamline the CI/CD process by leveraging the available variables. Is it possible to automate this process by dynamically reading these va ...