Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 route param into data

I have a simple route with 1 parameter:

{
    path: 'item/:id',
    component: ItemComponent,
    data: {title: 'Item detail'}
}

I'm setting page title using data title property in main AppComponent:

export class AppComponent implements OnInit {
    title: string;

    ngOnInit() {
         this.router.events
         .. parse it
         .subscribe((event) => {
                this.title = event['title'];
         });
    }
}

Then I'm just displaying it in AppComponent template:

<h1>{{ title }}</h1>

The problem is if I want to have dynamic title like "Item detail #name(:id)". Is there any way how can I add e.g. route param (:id) or variable into data title property? Something like

{
    path: 'item/:id',
    component: ItemComponent,
    data: {title: 'Item detail #' + :id }
}
like image 960
dontHaveName Avatar asked Feb 15 '17 09:02

dontHaveName


People also ask

How will you extract route parameters?

To extract the parameter, you need to make the dynamic parameter in the route path so that you can extract the value of the parameter by parameter name.

Can we pass data in router outlet in Angular?

There are various ways by which we can pass data from one component to another. Angular 7.2. 0 introduced a new way to pass data using State Object while navigating between routed components.


1 Answers

Like I said in the comments, you could keep the data.title param as a blueprint and replace the dynamic part from within the component.

Route declaration:

{
  path: 'item/:id',
  component: ItemComponent,
  data: { title: 'Item detail [id]' }
}

In data.title, I wrote [id] to make replacement easier but feel free to use whatever symbols you'd like to delimitate the string to replace.

Then, in the component:

export class AppComponent {
  title: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    const titlePattern = this.route.snapshot.data['title'];
    const id = this.route.snapshot.params['id'];
    this.title = titlePattern.replace('[id]', id);
  }
}
like image 57
AngularChef Avatar answered Oct 10 '22 00:10

AngularChef