Blog>
Snippets

Dealing with Angular Universal SEO

Provide examples of how to optimize Angular Universal pages for search engines by rendering metadata and improving semantic HTML on the server.
import { Meta, Title } from '@angular/platform-browser';

// Inject Meta and Title into your component or service constructor
constructor(private meta: Meta, private title: Title) {}

// Set the title and metadata in your SSR-enabled Angular component
ngOnInit() {
  this.title.setTitle('My Universal App - HomePage');
  this.meta.addTags([
    { name: 'description', content: 'This is my Angular Universal app for SEO' },
    { property: 'og:title', content: 'My Universal App - HomePage' },
    { property: 'og:description', content: 'Detailed description of the content of the page' },
    { property: 'og:image', content: 'https://example.com/image.jpg' },
    // Add more Open Graph or other SEO-relevant meta tags here
  ]);
}
This code uses Angular's Meta and Title services provided by the '@angular/platform-browser' package to set the HTML document's title and meta tags which are important for SEO. It adds a title, description, and Open Graph tags, typically run during server-side rendering with Angular Universal.
import { TransferState, makeStateKey } from '@angular/platform-browser';

// Define a state key to transfer data from server to the client
const SOME_STATE_KEY = makeStateKey('some_data');

// Inject TransferState into Angular component or service
constructor(private state: TransferState) {}

// Store some data in server-side render
this.state.set(SOME_STATE_KEY, someData);

// Retrieve the stored data in the client-side
ngOnInit() {
  const someData = this.state.get(SOME_STATE_KEY, defaultData);
}
This snippet uses Angular's TransferState service to transfer data from the server to the client, which helps in keeping the rendered content consistent and SEO-friendly during server-side rendering. Data is stored under a key on the server, and then retrieved on the client.
import { Injectable } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';

@Injectable({
  providedIn: 'root'
})
export class SeoService {

  constructor(private meta: Meta, private title: Title) {}

  // Use this service to update meta tags dynamically
  updateTitle(title: string) {
    this.title.setTitle(title);
  }

  updateMetaTags(tags: Array<{ name: string; content: string }>) {
    tags.forEach(tag => {
      this.meta.updateTag({ name: tag.name, content: tag.content });
    });
  }
}
This code creates a reusable SEO service to update the document title and meta tags dynamically. This service can be injected into different components or services to change the SEO-relevant information as needed.