Tips for transmitting static information from route configuration to components

I am facing an issue with passing static data from a route to a component in Angular. Despite trying to pass the data in the route configuration, I keep receiving empty data when subscribing to it from the ActivatedRoute. Below is the code snippet that I have implemented:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from '../../app.component';
import { CompanyInformationComponent } from '../../components/pages/company/company-information/company-information.component';
import { CompanyDescriptionComponent } from '../../components/pages/company/company-description/company-description.component';

const routes: Routes = [
  { path:'', redirectTo: 'company-information', pathMatch: 'full', data: { title: 'Company Information' } },
  { path:'company-information', component: CompanyInformationComponent, data: { title: 'Company Information' } },
  { path:'company-description', component: CompanyDescriptionComponent, data: { title: 'Company Description' } },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [
    RouterModule
  ],
  providers: [

  ]
})
export class routingModule { }

This is the code for my header component:

import { Component, OnInit } from '@angular/core';

import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'site-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  constructor( private route:ActivatedRoute ) {}

  ngOnInit() {
    this.route.data.subscribe(
      data => {
        console.log('Title',data);
      }
    )
  }
}

Answer №1

To obtain data, utilize route.snapshot.data

It is also important to include Router for monitoring router.events. Your constructor should be as follows:

constructor (private router : Router, private route : ActivatedRoute) {}

Furthermore, in the OnInit method:

ngOnInit() {
    this.router.events
        .filter(event => event instanceof NavigationEnd)
        .subscribe(
            () => {
                console.log(this.route.snapshot.data) // This will output { title: 'Company Information'}
            }
    );
}

Answer №2

You have the option to easily transmit data via routing by following this method:

For instance:

path: 'company-information/:valueToTransmit',

Inside your component:

import { ActivatedRoute } from '@angular/router';

[...]

constructor(protected route: ActivatedRoute){
 this.route.params.subscribe((params) => {
      if (params.valueToTransmit) {
        this.localData = params.valueToTransmit;
      }
    });
}

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

What is the most effective approach to scan Angular 2, 4, 5 template html files before AOT compilation for optimal code quality assessment?

Recently, I stumbled upon an interesting GitHub repository called "gulp html angular validate". If you're not familiar with it, you can check it out here. However, I have doubts about whether this tool is suitable for Angular 2+ projects. Additionall ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

What is the impact on active subscriptions when the browser is closed or refreshed?

Within the app component (the root component) of an Angular application, I have a few subscriptions set up. Since the app component remains active and is never destroyed until the application is closed, the ngOnDestroy method of the app component does not ...

"Data in Fusioncharts appears to be correctly formatted, but it is having difficulties

I am developing a financial analysis tool and I need to visualize stock data using fusion charts. Currently, my dataset includes stock values along with their respective dates: $scope.chartData = [ { "label": "2017-05-11 16:00:00", "value": "930.6" } ...

Guide to automatically installing @types for all node modules

As a newcomer to Typescript and NodeJs, I have been experiencing errors when mentioning node modules in my package.json file and trying to import them. The error messages I always encounter are as follows: Could not find a declaration file for module &apos ...

What is the most effective way to retrieve the value of a child component in Angular 2 and pass it to the parent component?

I am working on a project with a child component (calendar) and a parent component (form). I need to select a value in the calendar and then access that value in the form component. What is the best way to achieve this? Child Component.ts: import { ...

Encountering Issues with Accessing Property

Upon trying to run my code, the console is displaying an error that I am unable to resolve. The error specifically states: "TypeError: Cannot read property 'author' of undefined." View the StackBlitz project here The error seems to be coming fr ...

Guidelines for redirecting to a complete URL

I am currently developing a web application using Angular 7. One of the features I need to implement is redirecting to a full URL that is retrieved from a database. The challenge here is to perform the redirect within the app without causing a full page re ...

Exploring Angular2: A Guide to Interpolating Expressions in Templates

Is it possible to interpolate different types of Javascript expressions? Along with displayed properties like object.property and short expressions such as {{1+1}}, what other valid Javascript expressions can be used for interpolation? ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

A crucial error happened: The module "@angular-devkit/build-angular" could not be located within the directory "/ang-frontend". This issue arose while utilizing docker and docker-compose

When I attempt to run an angular application in docker-compose, I encounter an error, yet strangely, the error does not occur when running with docker run. docker-compose Ang-frontend | Ang-frontend | > <a href="/cdn-cgi/l/em ...

Combining portions of objects in Angular2

I want to combine two identical type observables in Angular2 and return an observable of the same type in a function. My goal is to: transform this setup: obs1.subscribe(obs => console.log(obs)) (where I receive): { count: 10, array: <some ...

Navigate through collections of objects containing sub-collections of more objects

The backend is sending an object that contains an array of objects, which in turn contain more arrays of objects, creating a tree structure. I need a way to navigate between these objects by following the array and then back again. What would be the most ...

Having trouble correctly displaying a form with nested form array within a form group

I am working with a form group that contains nested form groups and a form array: ngOnInit() { this.form = this.fb.group({ dropDownOptions: this.fb.group({ items: this.fb.array([this.createItem()]) }) ...

Tips for conducting a worldwide search in Angular 2?

I'm currently navigating my way through angular2 development and I am aiming to conduct a comprehensive search within an array of JSON objects. To illustrate, consider this sample array: invoiceList = [ { invoiceNumber: 1234, invo ...

Unable to transform the singular JSON object received from the server into the necessary format in order to analyze the data

Forgive me if my questions seem simple, as I am new to working with Angular. I'm having trouble understanding how to handle a JSON object received from the server and convert it into a custom datatype to use for rendering HTML using ngFor. I've ...

Issue encountered while setting up controls and AbstractControls in form development

Here is a snippet of code showing how I create and manipulate a form in Angular: this.myForm = new FormGroup({ points: new FormArray([ new FormGroup({ date: this.date, startTime: new FormControl(null, Val ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

Is the select all checkbox causing disabled checkboxes to be selected in an Angular environment?

<div *ngIf="showLog"> <!-- <p *ngIf="metricExecutionList Blockquote ===null">No Records Found</p> --> <div> <p-table #dt [value]="metricExecutionList" [l ...