Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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.

like image 424
Deepender Sharma Avatar asked Feb 15 '17 07:02

Deepender Sharma


1 Answers

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.

like image 130
Sachin Dudhankar Avatar answered Sep 21 '22 19:09

Sachin Dudhankar