6

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 }
}
8
  • 1
    I don't think so. But you can keep the data.title param as a "blueprint" and do a search/replace from within the component. Commented Feb 15, 2017 at 9:55
  • Is it possible to replace it within ItemComponent? Commented Feb 15, 2017 at 10:03
  • Yup. I posted an answer with some code. Any specific reason why you're using router.events to extract the route data/params? (instead of just route.data and route.params) Commented Feb 15, 2017 at 10:39
  • Router events are used for every route change. Commented Feb 15, 2017 at 10:40
  • Sure, but in your case you don't want to watch ALL router events, you just want to extract specific route properties and these properties are directly available on ActivatedRoute(.snapshot). Commented Feb 15, 2017 at 10:41

1 Answer 1

4

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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, but it would not make any sense replacing it inside AppComponent because there might be xx routes with same pattern. Would be better if I change it inside each FeatureComponent so I decided to create a service for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.