0

I'm trying to migrate my Angular App to an Angular SSR for better SEO. I need to provide the html's lang attribute depending on the route :

  • If the route starts with /fr, set it to fr
  • If the route starts with /en, set it to en

I think I have to use this in my AppComponent :

public readonly document = inject(DOCUMENT);

constructor() {
    this.document.documentElement.lang = myLanguage;
}

But I have no idea how to retrieve the route to know which language I should set.

1 Answer 1

1
...
  private document = inject(DOCUMENT);
  private router = inject(Router);
  private platformId = inject(PLATFORM_ID);

  constructor() {
    if (isPlatformBrowser(this.platformId)) {
      this.router.events
        .pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd))
        .subscribe((event: NavigationEnd) => {
          this.setLangFromUrl(event.urlAfterRedirects);
        });
    } else {
      // SSR: no router events, so use the initial URL
      const url = this.router.url;
      this.setLangFromUrl(url);
    }
  }

  private setLangFromUrl(url: string) {
    const lang = url.startsWith('/fr') ? 'fr' : url.startsWith('/en') ? 'en' : 'en';
    this.document.documentElement.lang = lang;
  }

...
Sign up to request clarification or add additional context in comments.

2 Comments

Thats strange. using NavigationEnd must output the correct url. On the server, router.url should contain /fr or /en. Ensure req.url is passed correctly in your server.ts: app.get('*', (req, res) => { res.render(indexHtml, { req, res, //... }); });
Sorry you were right, I deleted my previous component. const url = this.router.url; was returning nothing, but router.events did the job

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.