Angular 2 route parameters to data

I have a simple route with 1 parameter:

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

I set the page title using the data header property in the main AppComponent:

export class AppComponent implements OnInit {
    title: string;

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

Then I just show it in the AppComponent template:

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

The problem is that I want to have a dynamic name, for example "Item detail #name(:id)". Is there any way I can add, for example. route param (: id) or variable in data header property? Sort of

{
    path: 'item/:id',
    component: ItemComponent,
    data: {title: 'Item detail #' + :id }
}
+4
source share
1 answer

As I said in the comments, you can save the parameter data.titleas a drawing and replace the dynamic part inside the component.

Route Announcement:

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

data.title [id], , , .

:

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);
  }
}
+2

Source: https://habr.com/ru/post/1669808/


All Articles