Matheus Andrade
Matheus Andrade

Reputation: 99

Dinamically update meta tags for social share in angular4

I'm running into a problem and I want to know which approachs are more recommended to fix it. I'm using MetaService within angular 4 for update dinamically the 'meta' tags in components that will be shared in social media, however, facebook sharer, for example, doesnt recognize the updated values and loads the default values of my tags in dialog share. So, I ask, which ways fix this?

Upvotes: 0

Views: 1095

Answers (2)

beachCode
beachCode

Reputation: 3510

The Facebook and Twitter crawlers (unlike Google) do not execute any JavaScript, so you have to do this via server-side rendering. I did it by switching to Angular Universal and then using MetaService.

Note that porting to Angular Universal can be a major change, so do your research before deciding if you want to make the leap.

Upvotes: 1

KvD
KvD

Reputation: 448

Angular is SPA (Single Page Application) meaning the client will only fetch content from the server once and then handle routing to different pages in the client.

Under the hood the webserver is configured to route all traffic to one html file which is /index.html containing the code for the application. What you need is a way to serve different meta tags based on the initial request url. The two options I know of are:

Using server side rendering

Using server side rendering, Angular will produce static pages for each route which enables you to set specific meta tags for each route as well.

See this tutorial on converting your application to use server side rendering

Using Node.js, Express & ejs to inject meta data into index.html

Using the ejs library with Express you can dynamically inject meta tags into your index.html

Using ejs you will rename your index.html to index.ejs and configure it to contain variables

<title>
<%=title%>
</title>
<meta itemprop="description" content="<%=description%>">

Configure Express to use ejs to deliver different meta data based on requested url

router.get('/pageOne', function(req, res, next) {

var metaData = {
       title: 'Page One',
       descriptio: 'This is page one'
   };

res.render('index.ejs', metaData );
});

router.get('/pageTwo', function(req, res, next) {

var metaData = {
       title: 'Page two',
       descriptio: 'This is page two'
   };

res.render('index.ejs', metaData );
});

Upvotes: 2

Related Questions