Rose18
Rose18

Reputation: 3162

Angular Universal: Title and meta tags and not updated in Page Source

In my Angular Universal Application I am trying to update title and meta tags after the api call success.

app.component.ts

import {Component, Inject, OnInit, PLATFORM_ID} from '@angular/core';
import {Meta, Title} from '@angular/platform-browser';
import {isPlatformBrowser} from '@angular/common';
import {TestService} from './test.service';

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

  constructor(private testService: TestService,
              private title: Title,
              private meta: Meta,
              @Inject(PLATFORM_ID) private platformId: Object) {
  }

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      this.testService.getData().subscribe((res: any) => {
        console.log(res);
        this.title.setTitle(res.name);
        this.meta.updateTag({property: 'og:title', content: res.name});
      });
    }
  }
}

In the service...

  getData() {
    return this.http.get('assets/data.json');
  }

Title and tags are updated in inspect element but not in view page source.

Any suggestions are appreciated.

Upvotes: 2

Views: 2872

Answers (3)

Use the resolver if the api call is having the http request it will be more complex to render the title before route navigation by using the resolve guard you can get the title before the route navigation so SSR will helps to set the title before rendering page by implementing this you can get updated title in view page source! and which you're observing updated title in inspect elements is the title updating after rendering the page

Upvotes: 0

Sai Aduri
Sai Aduri

Reputation: 1

I think you can use this module - ngx-meta

https://www.npmjs.com/package/@ngx-meta/core

then, use this in your api call - this.title.setTitle(res.name);

Upvotes: 0

David
David

Reputation: 34435

Your if (isPlatformBrowser(this.platformId)) condition means that the code after is only executed client side, not while performing SSR. The code displayed in view-source is the code generated by SSR.

You need to remove that condition. And also, getData must call an absolute url when using universal

Upvotes: 4

Related Questions