Nick Hodges
Nick Hodges

Reputation: 17118

How do I access the data property of a Route in Angular?

I have the following code:

https://stackblitz.com/github/NickHodges/datademo

I am trying to display the data for a route on the page.

As you can see from the code, I have declared the path info like so:

const routes: Routes = [
  {
    path: 'comp1',
    component: Comp1Component,
    data: { info: 'Data from Comp1' }
  },
  {
    path: 'comp2',
    component: Comp2Component,
    data: { info: 'Data from Comp2' }
  }
];

I have declared a component like this:

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

@Component({
  selector: 'app-comp1',
  templateUrl: './comp1.component.html',
  styles: []
})
export class Comp1Component implements OnInit {
  constructor(public route: ActivatedRoute) {}

  ngOnInit() {}
}

and I am trying to access the data property like so:

<p>
  comp1 works!
</p>
<p>Comp1Data: {{ route.data['info'] }}</p>

So I go to the /comp1 route, but the data is not displayed.

How can I display the data property on a Route?

Upvotes: 5

Views: 6776

Answers (2)

Chris Barr
Chris Barr

Reputation: 34022

I need to do this in my app.component so it's always listening for route and data changes.

private readonly destroyRef = inject(DestroyRef);
private readonly router = inject(Router);
  
ngOnInit(): void {
  this.router.events
    .pipe(takeUntilDestroyed(this.destroyRef))
    .subscribe((event) => {
      if (event instanceof NavigationEnd) {
        const routeData = this.router.routerState.root.firstChild?.snapshot.data;
        if (routeData) {
          console.log(routeData);
          //You will have to cast `routeData['foo']` to whatever types you are using here since it will not be know by the type system
        }
      }
    }
}

Note that I am using inject() instead of constructor parameters, but it's the same thing.

Also note that the takeUntilDestroyed(this.destroyRef) may not be needed but I figure it's good practice.

Upvotes: 1

Jason White
Jason White

Reputation: 5813

The data attribute on an ActivatedRoute is an Observable and you need to subscribe to it.

comp-1.component.ts

export class Comp1Component implements OnInit {

  public data;   

  constructor(public route: ActivatedRoute) {}

  ngOnInit() {
    this.route.data.subscribe(data => this.data = data);
  }

}

comp1-component.html

<p *ngIf="data">Comp1Data: {{ data.info }}</p>

https://angular.io/api/router/ActivatedRoute#data

https://stackblitz.com/edit/github-4p1j6c

Upvotes: 6

Related Questions