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

The clash between Kendo UI and jQuery UI

I implemented Kendo UI for the date picker, and I'm looking to incorporate jQuery UI for the autocomplete feature. Upon adding the jQuery auto complete to my code, I encountered the following error: Uncaught TypeError: Cannot read property 'e ...

Click on the button to generate a PDF report using Internet Explorer 11

After encountering some challenges with printing a PDF report specifically on IE 11, I am reaching out for help. The code snippet below works perfectly in Chrome, but when it comes to IE 11, everything falls apart. Just to provide some context, I am develo ...

Timer for searching webpages using Javascript

I am looking for a way to continuously search a specific webpage for a certain set of characters, even as the text on the page changes. I would like the program to refresh and search every minute without having to keep the webpage open. In addition, once ...

Chart showing a Google Timeline: Allow for each bar to be colored differently when there are multiple bars on the same line

It appears that the Google Timeline charts have a feature to color individual blocks on the timeline as indicated in the documentation at However, there seems to be an issue when two bars overlap on the same line, which is evident in this fiddle: http://j ...

Disabling the ability to edit the rightmost portion of an input number field

I am looking for something similar to this: https://i.stack.imgur.com/ZMoNf.jpg In this case, the % sign will be shown in the input field by default and cannot be changed or removed. The user is only able to modify the number to the left of the % sign. P ...

Identifying the completion of scrolling within a container

I'm facing a challenge with my dynamic website that has numerous blog posts. My goal is to initially load only four posts and then add another four as the user scrolls to the end of the page. While I have figured out how to handle this on the backend, ...

javascript popup appears twice in IE when using PHP

After testing this script on multiple browsers, an issue arises when using IE. In all other browsers, the form submission alert only appears once. However, in Internet Explorer, the alert pops up twice. What could be causing this discrepancy? <!DOCTYP ...

Can you help me figure out how to retrieve the index of a CSS element during a 'click' event?

I have a collection of images all tagged with the class thumb. When a user clicks on one of these images, I need to determine which image was clicked within the array of thumbs. Essentially, I am looking for the index of the clicked image within the thumbs ...

Employing plain Javascript (without the use of jQuery) to concatenate information from two JSON strings - encountering an error due to the absence of

Having a JSON stringified form data like this: {"name":"jack miller", "address":"123 main st"} I aimed to append more records but encountered an error saying "append is not a function." The desired outcome is to have both sets of records in this format: ...

js extracting information from the XML response using response.text()

Currently, I am sending an ajax request to an API that returns data in XML format. Upon receiving the responseXml data, it gets displayed, but I'm unsure about how to parse it and access specific data elements such as item.line or item.origTime. Shou ...

Restricting array elements through union types in TypeScript

Imagine a scenario where we have an event type defined as follows: interface Event { type: 'a' | 'b' | 'c'; value: string; } interface App { elements: Event[]; } Now, consider the following code snippet: const app: App ...

Utilizing array iteration to display images

I am having trouble getting the images to display on my card component. The description appears fine, but the images are not rendering properly even though I have the image data in an array. Here is the Card Component code: export const Card = (props) =&g ...

Using jQuery to remove the last two characters from a specified class

I have a simple task at hand. I am trying to use the slice method in JavaScript to remove the last two characters from a string that is generated dynamically within a shopping cart. Instead of displaying a product as $28.00, I want it to display as $28. S ...

Establish a secure connection to MySQL through SSH tunneling with node-mysql

Is it feasible to establish a connection to the MySQL server using an SSH key instead of a password when utilizing the node-mysql npm package? ...

When sending a response using res.send, it is not possible to include all properties of

I'm working with an API controller method that looks like this: let object = { "key1": "value1", "key2": "value2", "arrayKey": [ { "arrKey": "arrValue", "arrKey1": 1 } ] } export const foo = ...

verify this condition prior to executing the for loop in javascript

When working with a queue in Typescript (ES6) set to run on an interval of 1 ms, it's important to consider the most efficient approach for performance. 1. setInterval(() => { //if (this._queue.filter(a => !a.running && a.cbs.length) ...

"eliminate" ng-if after the condition becomes true

I'm curious to know if it's possible to deactivate or remove ng-if once its value becomes true? In my project, I've constructed a tree structure using a recursive directive. Each branch in the tree has a <div ng-if="visible"> element ...

The constant LOCALE_ID is always set to en-US and remains unchanged

app.module.ts import { registerLocaleData } from '@angular/common'; import localeIndia from '@angular/common/locales/en-IN'; import additionalLocaleIndia from '@angular/common/locales/extra/en-IN'; registerLocaleData(localeInd ...

Can you guide me on implementing AWS SDK interfaces in TypeScript?

Attempting to create an SES TypeScript client using AWS definitions file downloaded from this link My approach so far: /// <reference path="../typings/aws-sdk.d.ts" /> var AWS = require('aws-sdk'); var ses:SES = new AWS.SES(); The error ...

Tips for incorporating a multimedia HTML/JavaScript application within C++ programming

I possess the source code for a JavaScript/HTML5 application that operates on the client-side and manages the transmission/reception of audio and video data streams to/from a server. My objective is to develop a C++ application that fully integrates the c ...