In the ionic project, there is only one head
section where we write all the meta tag
that is in the index.html
page. For example, to make the Facebook sharing work perfectly we need this meta tag
given bleow:
<meta property="og:title" content="Title">
<meta property="og:description" content="description">
<meta property="og:image" content="Image Url you want to show">
<meta property="og:url" content="http://yourUrl.com">
So how can we update this meta tag from other pages? For example, if we go to a news detail
page the meta tag
of that page will be changed accordingly. So how can I achieve this in my Ionic4 with angular project?
In my existing Ionic 4
project, I want to use Angular Universal
but I got into so many errors. So I created a new project using Ionic 5
. And move all my previous work to the new Ionic 5
. I follow these steps to add Angular Universal
to my project.
At first, create an app and update it to the latest version of Angular using these commands.
ionic start myApp blank --type angular
cd myApp
ng update @angular/core @angular/cli
npm install @angular/animations
Then add Express engine
for Angular Universal
using this command.
ng add @nguniversal/express-engine
Then you need to install the @ionic/angular-server
module using this command.
npm install @ionic/angular-server@dev
For testing in the localhost, your server-side rendering is working correctly you need to use this command.
npm run dev:ssr
For more detailed information on how to setup Angular Universal for server-side-rendering you can see the ionic blog
link SSR with Angular Universal And Ionic.
After setting, angular universal you need to add title
, add
, or update
meta tag
. You can follow my sample code given below:
import { Component, OnInit} from '@angular/core';
import { Title, Meta } from '@angular/platform-browser';
@Component({
selector: 'app-sample',
templateUrl: './sample.page.html',
styleUrls: ['./sample.page.scss'],
})
export class SamplePage implements OnInit {
constructor(private titleService: Title, private meta: Meta) { }
ngOnInit() {
this.titleService.setTitle("Your Title");
this.meta.updateTag({ property: 'og:url', content:'http://yoururl.com'});
this.meta.updateTag({ property: 'og:title', content:"Your Title" });
this.meta.updateTag({ property: 'og:image', content: "your image link"});
this.meta.updateTag({ property: 'og:description', content: "description"});
}
}
Now your social share will work perfectly. Because when it crawls not it will get the metatag with data. You need to update the meta tag based on the social share you want to add.