Skip to content

Instantly share code, notes, and snippets.

@anop72
Forked from LA1CH3/seo.service.ts
Last active October 11, 2016 23:19
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 anop72/46388d628b8265fc36e4601ff7c4a3cc to your computer and use it in GitHub Desktop.
Save anop72/46388d628b8265fc36e4601ff7c4a3cc to your computer and use it in GitHub Desktop.
set meta tag on angular 2 single page application
/*
SEO Service for Updating Title, Meta Tags, Etc.
*/
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 {
private titleService: Title;
private headElement: HTMLElement;
private metaDescription: HTMLElement;
private robots: HTMLElement;
private canonical: HTMLElement;
private DOM: any;
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');
this.canonical = this.getOrCreateLinkElement('canonical');
}
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);
}
public setCanonical(link: string) {
this.canonical.setAttribute('href', link);
}
/**
* 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);
this.headElement.appendChild(el);
}
return el;
}
private getOrCreateLinkElement(name: string): HTMLElement {
let el: HTMLElement;
el = this.DOM.query('link[rel=' + name + ']');
if (el === null) {
el = this.DOM.createElement('link');
el.setAttribute('rel', name);
this.headElement.appendChild(el);
}
return el;
}
}
@panbanda
Copy link

Has something changed with this? I am getting dom_adapter.js:8Uncaught SyntaxError: Unexpected token import at line 8 with import { isBlank } from '../facade/lang'; which makes me think its a babel issue, but I have babel and everything is working without this import. Is this different now?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment