Search code examples
angulartypescriptangular-router

Path variable to use in data in Angular


i have a problem with tab title setting. Before is was always the same title which is set in index.html

Now i would like to have another title in some components and wanted to and using data routes for it, but is it possible to take :userId from path directly in data?

{ path: 'users/user-details/:userId', component: UserDetailsComponent, canActivate: [AuthGuard], data : {title:'User - '}}

So the tab title should look like this

User - 1234 or User - :userId

Thanks in advance


Solution

  • If I understand correctly, you want to set the document title dinamically based on the route params.

    You can use Title service to achieve that.

    Register it on the module providers:

    @NgModule({
      imports: [BrowserModule],
      declarations: [AppComponent],
      providers: [Title],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    Inject it on your component:

    export class UserDetailsComponent implements OnInit {
      public constructor(private title: Title, private route: ActivatedRoute) { }
    
    

    Then retrieve data from the activated route and pass it to the setTitle method:

    ngOnInit() {
        const title: string = route.snapshot.data.title;
        const userId: string = route.snapshot.params.userId;
        this.title.setTitle(title + userId);
    }
    

    In this example I'm using the route snapshot but you might want to subscribe to the route observables instead.