Skip to content

Instantly share code, notes, and snippets.

@LA1CH3
Created July 7, 2016 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LA1CH3/718588765d56a8932de52c64c3561dcf to your computer and use it in GitHub Desktop.
Save LA1CH3/718588765d56a8932de52c64c3561dcf to your computer and use it in GitHub Desktop.
/*
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 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');
}
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);
this.headElement.appendChild(el);
}
return el;
}
}
@goelinsights
Copy link

Have you been able to set rel="canonical" with the same approach?

@anop72
Copy link

anop72 commented Aug 11, 2016

Yes, you can do the same approach.

@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?

@u12206050
Copy link

I am having the exact same issue as @jylinman:

 import { isBlank } from '../facade/lang';
^^^^^^
SyntaxError: Unexpected reserved word

However I am not using babel, using typescript, webpack and universal.

Copy link

ghost commented Oct 24, 2016

Hi, i am trying to set og:local but that doesnt work. How can i set it?

@PaKosim
Copy link

PaKosim commented Mar 13, 2017

How to create element meta property and og:title?

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