Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so:

..
...
<section class="ka-cockpit-panel cockpit-1 pull-left">
            <ka-cockpit-panel></ka-cockpit-panel>
</section>
...
..

Within this component, our goal is to access the current active route data.

For example, if we have another component (let's say ka-integration-component) with associated route data (as illustrated below), whenever we navigate to this component (via URL or by clicking a router link), we aim to retrieve the integration component route data in our ka-cockpit-component.

 ..
    ... 
    {       
        path: "",       
        component: IntegrationComponent,
        data : {
            cockpit1 : false,
            cockpit2 : true,
            kpi : true
        },  
    }
    ..
    ...

In essence, our objective is to configure our ka-cockpit-component for specific components within our application that are linked to certain routes so that we can modify its visibility/appearance as needed.



Cockpit component code :

import { Component, OnInit } from '@angular/core';
import { Router,Event,NavigationEnd,ActivatedRoute } from '@angular/router';

@Component({
    selector: 'ka-cockpit-panel',
    templateUrl: './cockpit-panel.component.html',
    styleUrls : ['./cockpit-panel.component.scss']
})
export class CockpitPanelComponent implements OnInit {

    constructor(private router:Router,private activatedRoute : ActivatedRoute) {
         this.router.events.subscribe( (event:Event) => {
            if(event instanceof NavigationEnd) {
                console.log("Cockpit Panel Component : Route successfully changed -  ",event,this.router,this.activatedRoute);

                  // THIS IS WHAT WE WANT - get  Integration component route data here whenever i navigate to integration component!!!

            }
        });
     }

    ngOnInit() { }
}

Answer №1

If you are looking to implement a specific feature, use the Resolve Guard.

// MyDataResolver Service

import { Injectable }             from '@angular/core';
import { Router, Resolve, RouterStateSnapshot,
         ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class CustomResolver implements Resolve<any> {
  constructor(private cs: CustomService, private router: Router) {}
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> {

    let pathFromRoot = route.pathFromRoot;

    // Customize your data based on the route

    return Promise.resolve({
        setting1 : false,
        setting2 : true,
        option : true
    });

  }
}

// Routing configuration

.
.
{       
    path: "",       
    component: MainComponent,
    resolve : {
        customData: CustomResolver
    },  
}
.
.

// Component

export class SettingsPanelComponent implements OnInit {
  displayText : string = "Sample Text";

  constructor(private router:Router,private activatedRoute : ActivatedRoute) {

    this.activatedRoute.data.subscribe( (res) => {

      // Access data retrieved from resolve guard here
      console.log(res);

    });
  }

  ngOnInit() { }
}

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

Elasticsearch query fails to execute when encountering a special character not properly escaped

I am facing an issue with querying a keyword that includes a dot (.) at the end. While the query works perfectly on Kibana's console, it fails to execute on my application's function. The following function is responsible for creating the query b ...

I'm torn between whether to calculate on the client side for more requests or on the server side for fewer requests. What should I do?

Consider this scenario: I am developing a shopping cart application where I need to store information such as idClient, createdAt, total, and products in each purchase. In addition, I need to apply discounts on the products for each purchase. This is how ...

End the div element upon completion of the Vimeo video

I am in need of a website that includes an intro video displayed as a full-width div over the background content. To achieve this, I created a Div containing an iframe video from Vimeo along with a button to skip the intro (which closes the div upon clicki ...

What could be the reason for NPM failing to work following an update?

Just two days ago, I updated NPM and now it's suddenly not working on my Windows 10 20H2 platform. Every action I take results in the same error message: C:\Users\ethan>npm internal/modules/cjs/loader.js:883 throw err; ^ Error: Canno ...

What is the best way to indicate a particular element within a subdocument array has been altered in mongoose?

I have a specific structure in my Mongoose schema, shown as follows: let ChildSchema = new Schema({ name:String }); ChildSchema.pre('save', function(next){ if(this.isNew) /*this part works correctly upon creation*/; if(this.isModifi ...

Sending a parameter to the window.onload callback function

Is there a way to pass parameters from ModelAndView to a window.onload function in JavaScript within an HTML file? Here is an example of how it can be done: @RequestMapping(value = "/admin/printtext") public ModelAndView printtext() { ModelAndView mo ...

ESLint is indicating an error when attempting to import the screen from @testing-library/react

After importing the screen function from @testing-library/react, I encountered an ESLint error: ESLint: screen not found in '@testing-library/react'(import/named) // render is imported properly import { render, screen } from '@testing-lib ...

Retrieve the Data from Input Fields with Matching Classes and Transmit to a Script Using AJAX Request

I am working on a form that includes multiple input fields: <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="da ...

How can we pass an optional boolean prop in Vue 3?

Currently, I am in the process of developing an application using Vue 3 and TypeScript 4.4, bundled with Vite 2. Within my project, there exists a file named LoginPage.vue containing the following code: <script lang="ts" setup> const props ...

Ways to activate flashlight on mobile using React.Js

Is it possible to control the torch light of a mobile device by toggling a button? https://i.stack.imgur.com/x9nIf.png <IconButton onClick={() => setFlashOn(!flashOn)} style={{ position: "absolute", right: 80, top: 20, zIndex: ...

Click the button to insert a time stamp into the text area

Whenever the id=dodaj_godzine_button is clicked, I would like to add the current time to id=formularz_wpis_tresc (as a string). I attempted to do this using the code below, but it seems to be malfunctioning. $("#dodaj_godzine_button").click(function(){ ...

Encountering Error with Axios in Nuxt while Navigating Pages

Working on a nuxt application utilizing axios for API calls. In my index.vue file, I have the code snippet below. <template> <div> <Hero /> <Homebooks :details="details" /> </div> </template> <s ...

Analyzing the string's worth against the user's input

I need help figuring out how to save user input on a form (email and password) as variables when they click "Register", so that the data can be used later if they choose to click "Login" without using default information. I am working on this project for s ...

Button in Angular gets stuck when a touchscreen is long pressed

In my Angular2 application, I am facing an issue with a button when running on a Windows 10 touchscreen PC in Chrome. Normally, the button works fine and executes the click function. However, if the button is held for 1-2 seconds, it gets stuck and fails t ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

Differences Between Angular 2 RC5 ngModules and Barrels

We are currently transitioning our project from Angular 2 RC4 to RC5. One important question arises: now that ngModules have been introduced, will barrels (index files) become obsolete? Can both be utilized simultaneously? How should we go about utilizin ...

Using the @ Symbol in Javascript ES6 Module Imports

One of the folders in my node_modules directory is called @mymodule, and within it, there is another folder named 'insidefolder'. The path to this folder looks like this: node_modules/@mymodule/insidefolder When trying to import insidefolder us ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

Using Bootstrap Select with a callback function

I am currently working with 2 Bootstrap Select dropdowns. One dropdown contains a list of countries, while the other contains a list of states. The country list is static and loads when the page is loaded. On the other hand, the state list is populated dyn ...

Pressing the button results in no action

I am currently developing a program that randomly selects 5 words from a database and inserts them into an array. Although the page loads correctly initially, nothing happens when the button is clicked. None of the alerts are triggered, suggesting that the ...