Skip to content

Instantly share code, notes, and snippets.

@SampsonCrowley
Created April 7, 2017 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SampsonCrowley/424af1c70a6700e80b1c51576eb023bd to your computer and use it in GitHub Desktop.
Save SampsonCrowley/424af1c70a6700e80b1c51576eb023bd to your computer and use it in GitHub Desktop.
/*
* This snippet is a global header service to set SEO meta tags with Angular 2
*/
import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { getDOM } from '@angular/platform-browser/src/dom/dom_adapter';
@Injectable()
export class SeoService {
/**
* Angular 2 Title Service
*/
private titleService: Title;
/**
* <head> Element of the HTML document
*/
private headElement: HTMLElement;
/**
* <meta name="description"> Element of the HTML document
*/
private metaDescription: HTMLElement;
/**
* <meta name="robots"> Element of the HTML document
*/
private robots: HTMLElement;
private DOM: any;
/**
* Inject the Angular 2 Title Service
* @param titleService
*/
constructor(titleService: Title){
this.titleService = titleService;
this.DOM = getDOM();
this.headElement = this.DOM.query('head');
this.metaDescription = this.getOrCreateMetaElement('description');
this.robots = this.getOrCreateMetaElement('robots');
}
public getTitle(): string {
return this.titleService.getTitle();
}
public setTitle(newTitle: string) {
this.titleService.setTitle(newTitle);
}
public getMetaDescription(): string {
return this.metaDescription.getAttribute('content');
}
public setMetaDescription(description: string) {
this.metaDescription.setAttribute('content', description);
}
public getMetaRobots(): string {
return this.robots.getAttribute('content');
}
public setMetaRobots(robots: string) {
this.robots.setAttribute('content', robots);
}
/**
* get the HTML Element when it is in the markup, or create it.
* @param name
* @returns {HTMLElement}
*/
private getOrCreateMetaElement(name: string): HTMLElement {
let el: HTMLElement;
el = this.DOM.query('meta[name=' + name + ']');
if (el === null) {
el = this.DOM.createElement('meta');
el.setAttribute('name', name);
el.setAttribute('property', "og:" + name)
this.headElement.appendChild(el);
}
return el;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment