How can I update the HTML header using ASP.NET Core SpaServices and Angular Universal?

1.3k views Asked by At

I am using the template at https://github.com/aspnet/JavaScriptServices/tree/dev/templates/Angular2Spa as a starting point for an Angular Universal SPA. It renders the Angular root component as follows:

@{
    ViewData["Title"] = "Home Page";
}

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

I'd like for some of my Angular components to modify the contents of the HTML header (such as setting the title tag, or adding additional meta tags).

Keeping in mind that the template uses Razor to render the head portion of the page, are there any suggestions on how this can be achieved?

The only thing I am using Razor to handle is the asp-append-version tag helper, so moving all of the HTML rendering into an Angular component would be an option (provided I had a way to maintain the cache-busting somehow).

Thanks in advance!

2

There are 2 answers

5
Sanket On

You can set the document or window title using the Title service.

Sample implementation-

import { Component } from '@angular/core';
import { Title }     from '@angular/platform-browser';

@Component({
selector: 'my-app',
template:
  `<p>
    Select a title to set on the current HTML document:
  </p>
  <ul>
    <li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
    <li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
    <li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
  </ul>
  `
})

export class AppComponent {
  public constructor(private titleService: Title ) { }
  public setTitle( newTitle: string) {
    this.titleService.setTitle( newTitle );
  }
}

Working plunker from angular documentation available here

0
Issac On

In aspnetcore-angular2-universal they implemented a nice meta.service.ts for dealing with manipulating the head stuff like title and meta tags. it works great at the client side, but unfortunately, as mentioned here, the service can be used only at the browser:

// Until we can get entire Html doc (this is a .NET issue since we never pass the entire Document (only root-app))

If not using aspnet core and sticking with angular universal on node this can be done as described here: https://stackoverflow.com/a/42377704/1694015

Consider that we need the title\meta tags rendered at the server only for the first call (for purpose of social crawlers - angular can take care of that on the client navigation after), will it be a good approach to detect the route at the mvc controller's action, and pass the title and meta with ViewData to the mvc view that is rendered and set it there?