Deepender Sharma
Deepender Sharma

Reputation: 490

Angular 2: How to add and update the meta tags dynamically from a component (like title service)

I am very new to Angular 2. I need to set up the meta tags like og: description and all from a component. I have no idea how to dynamically update the meta tags, also add new tags to the index.html from a particular component.

Please help.

PS: I read about title service, but that is to update the title only.

Upvotes: 13

Views: 11991

Answers (3)

Sachin Dudhankar
Sachin Dudhankar

Reputation: 71

In Angular 4 you can easily update your web page title and meta tag information.

  1. Import the predefined Meta Service in your component.

    import { Meta, Title } from '@angular/platform-browser';

  2. Inject the Service in Constructor.

constructor(private title: Title, private meta: Meta) {} 
  1. Add title and meta tag in ngOnInit() using setTitle and updateTag
 ngOnInit(){    
        this.title.setTitle('Angular Overview');    
        this.meta.updateTag({ name:'author',content:'angulartpoint.com'});    
        this.meta.updateTag({name:'keyword',content:'angular overview, features'});    
        this.meta.updateTag({name:'description',content:'It contains overview of angular application'});    
    }
  1. Check the head tag in the browser.

Upvotes: 7

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657248

In Angular4-beta.0 a Meta service was added that allows you to add/remove meta tags

import { Meta } from '@angular/platform-browser';

constructor(private meta:Meta) {
  meta.addTag(...)
}

For more details see

Upvotes: 8

santillanix
santillanix

Reputation: 2014

First import Meta service in your component

import { Meta } from '@angular/platform-browser';

Put it in the constructor

constructor(private Meta:Meta){}

Use the service:

this.Meta.addTag({ name: 'yourmetaname', content: 'yourmetacontent' });

you can look for more information in oficial DOCS:

https://angular.io/docs/ts/latest/api/platform-browser/index/Meta-class.html

Upvotes: 10

Related Questions