5

I am using "@angular/localize": "^9.0.2" and I have a route with a dynamic title which should be translated:

const routes: Routes = [
  { path: 'overview', component: DashboardPageComponent, data: { title:  $localize`:@@overview:Overview`, breadcrumb: 'Overview' } },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DashboardRoutingModule { }

messages.es.xlf

<unit id="overview">
  <segment>
    <source>Overview</source>
    <target>Vista general</target>
  </segment>
</unit>

But when I run ng serve --configuration=es, the following error is displayed:

ERROR in src/app/dashboards/dashboard-routing.module.ts(8,7): Error during template compile of 'DashboardRoutingModule'
  Reference to a local (non-exported) symbols are not supported in decorators but 'routes' was referenced
    Consider exporting 'routes'.

In addition, I read the article: https://blog.ninja-squad.com/2019/12/10/angular-localize/ looking for a workaround such as:

const routes: Routes = [
  { path: 'overview', component: DashboardPageComponent, data: { title: 'Overview', breadcrumb: 'Overview' } },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DashboardRoutingModule { }

@Component({
  selector: 'app-title',
  templateUrl: './title.component.html',
  styleUrls: ['./title.component.scss']
})
export class TitleComponent implements OnInit, OnDestroy {

  private subscription: Subscription;
  public title: String = "";

  constructor(    
    private router: Router,
    private activatedRoute: ActivatedRoute
  ) {
    this.title = this.translate(this.buildTitle(this.activatedRoute.firstChild));
  }

  ngOnInit() {
    this.subscription = this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      distinctUntilChanged(),
    ).subscribe(() => {
        this.title = this.buildTitle(this.activatedRoute.firstChild);
    });
  }

  ngOnDestroy() {
    if(this.subscription) {
      this.subscription.unsubscribe();
    }
  }

  buildTitle(route: ActivatedRoute): String {
    return route.routeConfig && route.routeConfig.data ? route.routeConfig.data.title : '';
  }

  translate(title: String): String {
    if(!title || title === '') return title;
    console.log(title);
    switch(title) {
      case 'Overview': return $localize`:@@overview:Overview`;
      // Other cases...
    }
  }
}

But in this case $localize:@@overview:Overview always displays 'Overview' but not the messages.es.xlf translation. Any idea about to how use $localize in order to translate this title?

Fran b
  • 3,016
  • 6
  • 38
  • 65
  • We ran into the same issue. Any $localize strings set in the router are not being picked up by angular for translation (although they are extracted via CLI). – Phil Thomas Feb 08 '21 at 10:15
  • 1
    Your first approach seems to work fine in Angular 12. – Roobot Sep 14 '21 at 18:43

0 Answers0