angularangular-universal

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.


Solution

  • 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