Skip to content

Instantly share code, notes, and snippets.

@tieppt
Last active November 9, 2023 14:29
Show Gist options
  • Save tieppt/4f417a287bcbbdccc75bbf60b2272788 to your computer and use it in GitHub Desktop.
Save tieppt/4f417a287bcbbdccc75bbf60b2272788 to your computer and use it in GitHub Desktop.
seo service Angular
import { Component } from '@angular/core';
import { SeoService } from 'path/to/seo.service';
@Component({
selector: 'app-root',
template: ``
})
export class AppComponent {
constructor(seoService: SeoService) {
seoService.setTitle('My awesome App Title!!!');
seoService.setMetaDescription('My awesome Metadesciption');
seoService.setMetaRobots('Index, Follow');
}
}
import { NgModule } from '@angular/core';
import { SeoService } from 'path/to/seo.service';
@NgModule({
providers: [
// ... other service
SeoService
]
})
export class AppModule {
}
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;
/**
* <head> Element of the HTML document
*/
private metaDescription: HTMLElement;
/**
* <head> 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();
/**
* get the <head> Element
* @type {any}
*/
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment