Skip to content

Instantly share code, notes, and snippets.

@wasteCleaner
Last active September 18, 2017 02:04
Show Gist options
  • Save wasteCleaner/205c818fd57d120dab46a2ae617e45ac to your computer and use it in GitHub Desktop.
Save wasteCleaner/205c818fd57d120dab46a2ae617e45ac to your computer and use it in GitHub Desktop.
import { Injectable, Inject } from '@angular/core';
import { DomAdapter } from '@angular/platform-browser/src/dom/dom_adapter';
import { __platform_browser_private__, DOCUMENT} from '@angular/platform-browser';
@Injectable()
export class SeoService {
private _dom: DomAdapter = __platform_browser_private__.getDOM();
constructor(@Inject(DOCUMENT) private _document: any) { }
setTitle(title: string) {
this._document.title = title
}
setMetaElem(name: string, value: string) {
let headTags = this._document.head.children as HTMLCollection;
for (let i = 0; i < headTags.length; i++) {
let elem = headTags[i] as HTMLElement;
if (elem.tagName === 'meta') {
let attr = elem['attribs'];
if ('name' in attr) {
if (attr.name === name) {
this._dom.remove(elem);
}
}
}
}
let el = this._dom.createElement('meta') as HTMLMetaElement;
this._dom.setAttribute(el, 'name', name);
this._dom.setAttribute(el, 'content', value);
this._dom.appendChild(this._document.head, el);
}
setOgElem(name: string, value: string) {
let headTags = this._document.head.children as HTMLCollection;
for (let i = 0; i < headTags.length; i++) {
let elem = headTags[i] as HTMLElement;
if (elem.tagName === 'meta') {
let attr = elem['attribs'];
if ('property' in attr) {
if (attr.property === name) {
this._dom.remove(elem);
}
}
}
}
let el = this._dom.createElement('meta') as HTMLMetaElement;
this._dom.setAttribute(el, 'property', name);
this._dom.setAttribute(el, 'content', value);
this._dom.appendChild(this._document.head, el);
}
}
///////////////////////////////////////
// example of import to app.module.ts
///////////////////////////////////////
import { SeoService } from './shared/seo.service';
@NgModule({
bootstrap: [ AppComponent ],
declarations: [],
imports: [],
providers: [
SeoService
]
})
///////////////////////////////////////
// example of use in components
///////////////////////////////////////
import { SeoService } from './shared/seo.service';
export class YourComponent {
constructor(private: seoService:SeoService) {
this.seoService.setTitle('Title text');
this.seoService.setMetaElem('description', 'Description text');
this.seoService.setOgElem('og:title', 'Title text');
this.seoService.setOgElem('og:description', 'Description text');
/* other og tags... */
}
}
@vforv
Copy link

vforv commented Mar 19, 2017

@wasteCleaner it works for title not for metatags what can be a problem?

@jdmaldonado
Copy link

In my case was because the tag name is 'META' not 'meta'

if (elem.tagName === 'META') {
    let attr = elem['attribs'];
    if (attr && 'name' in attr) {
    }
}

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