Adding Open Graph tags to your Angular app lets social platforms like Facebook, LinkedIn, and X (Twitter) show a rich preview—title, description, and image—when someone shares a link. This guide walks you through implementing dynamic OG tags for each route, using Angular’s built-in Meta service and a small helper for handling route changes.
What You’ll Need
- An existing Angular application (version 12 or later recommended)
- Angular Router set up with at least one route
- Basic familiarity with TypeScript and Angular services
- An image URL (typically 1200×630 pixels) for social previews
Step-by-Step
- Create a service for managing meta tags. Run
ng generate service services/og-tagsin your terminal. This creates a service file where you’ll centralize all Open Graph logic. - Inject Angular’s Meta and Title services. Open the generated
og-tags.service.tsand addMetaandTitlefrom@angular/platform-browserto the constructor: -
import { Injectable } from '@angular/core'; import { Meta, Title } from '@angular/platform-browser'; @Injectable({ providedIn: 'root' }) export class OgTagsService { constructor(private meta: Meta, private title: Title) {} } - Define a method that sets all OG tags. Add a public method, e.g.,
setOgTags(config: OgConfig), whereOgConfigis an interface with optionaltitle,description,image, andurlfields. Inside, usethis.title.setTitle()for the browser tab andthis.meta.updateTag()for each OG property. - Update or add each OG tag. For every property you want to set, call
updateTagwith the attribute selector. Example:this.meta.updateTag({ property: 'og:title', content: config.title }). Repeat forog:description,og:image,og:url, andog:type(usually ‘website’ or ‘article’). - Add a default set of OG tags. In the same service, create a method
setDefaultTags()that sets a fallback title, description, and image. Call this in your root component’sngOnInitso every page has at least basic tags before route-specific ones apply. - Set tags on each route change. In your main
AppComponentor a dedicated component, subscribe toRouter.events. Filter forNavigationEndevents, then map the current URL to your route data. You can attach OG values to each route’sdataproperty in your router config: -
{ path: 'product/:id', component: ProductComponent, data: { ogTitle: 'Product Page', ogDescription: 'View this product' } } - Read route data and apply tags. In the subscription, get the activated route snapshot via
router.routerState.snapshot.root, traverse its children to find the deepest route with data, and pass those values to your service’ssetOgTagsmethod. For dynamic values like a product name, fetch the data in the component itself and call the service after the data arrives. - Handle dynamic content. For pages that load data asynchronously (e.g., from an API), call
ogTagsService.setOgTags(...)inside thesubscribecallback of your HTTP request, after you have the real title and description. - Add Twitter Card tags (optional). Twitter uses its own tags if present. Add
twitter:card,twitter:title,twitter:description, andtwitter:imageusing the sameupdateTagmethod but withnameinstead ofproperty. - Test with a validator. After deploying, paste your URL into the Facebook Sharing Debugger or LinkedIn Post Inspector. These tools fetch your page and show which OG tags they detect. Use them to verify each tag appears correctly.
- Force re-scrape after changes. Social platforms cache OG tags. After updating tags, use the debugger’s “Scrape Again” button (Facebook) or append
?fbrefresh=CAN_BE_ANYTHINGto the URL being scraped to bust the cache.
Common Mistakes
- Forgetting to update the
og:urltag. If your app uses client-side routing, the URL in the OG tag must match the actual shared URL. Usewindow.location.hrefor the router’s current URL. - Using
addTaginstead ofupdateTag.addTagcreates duplicate tags if called multiple times.updateTagfinds an existing tag and replaces its content, or creates it if missing. - Setting tags only in the component. If the component’s
ngOnInitruns before the browser renders, crawlers may not see the tags. Set them as early as possible, ideally in a route guard or the router event subscription. - Using relative image paths. OG image URLs must be absolute (starting with
https://). A relative path like/assets/og-image.pngwill not work. - Ignoring the default tags. If a route doesn’t set its own tags, the previous route’s tags remain. Always have a fallback set of defaults.
Tips
- Create a reusable config object. Define an interface for your OG data and pass it around—it keeps your code clean and prevents typos in property names.
- Use Angular’s
Metaservice for all meta tags. It also handles standard meta tags likedescriptionandkeywords, so you can manage everything in one place. - Generate the OG image dynamically. If your app has many shareable pages, consider generating images on the fly using a service like a headless browser or an image generation API, then cache the URL.
- Set the
og:localetag. If your app supports multiple languages, addog:localeandog:locale:alternateto help platforms display the right language preview. - Test on a staging server. Social scrapers may not follow client-side redirects. Make sure your staging URL is publicly accessible before testing.
Troubleshooting
- Tags not appearing in the debugger. First, view the page source (Ctrl+U) and search for
og:. If the tags are missing, your Angular app is likely rendering them after the crawler fetches the HTML. Consider Angular Universal (SSR) or a pre-rendering solution like Scully to serve static HTML with tags embedded. - Tags appear but with old content. This is almost always caching. Use the debugger’s refresh/scrape-again feature. For Facebook, you can also append
?fbrefresh=CAN_BE_ANYTHINGto the URL in the debugger. - Image not showing. Verify the image URL is publicly accessible, not behind authentication, and is at least 200×200 pixels (1200×630 recommended). Check that the image format is supported (JPEG, PNG, WebP).
- Tags work in browser but not on social media. This happens when your app is a single-page application (SPA) and the crawler doesn’t execute JavaScript. The only reliable fix is server-side rendering or static pre-rendering for the routes you want to share.
- Duplicate tags in the DOM. If you see multiple
og:titletags, you’re likely callingaddTaginstead ofupdateTag, or the service is instantiated multiple times. UseupdateTagconsistently and ensure your service is provided at the root level.
Frequently Asked Questions
Do I need Angular Universal for OG tags to work?
Not necessarily. If you only care about link previews in modern chat apps that render JavaScript, client-side tags may suffice. However, Facebook, LinkedIn, and most crawlers do not execute JavaScript, so for reliable sharing, you need SSR or pre-rendering.
What is the ideal image size for OG tags?
Use 1200×630 pixels for the standard og:image. This aspect ratio (1.91:1) displays well on most platforms. Keep the file size under 8MB and use JPEG or PNG.
How do I set different OG tags for each product page?
Fetch the product data in your component, then call setOgTags with the product’s title, description, and image URL inside the HTTP subscription callback. This ensures the tags are set after the data is available.
Will OG tags affect my SEO ranking?
Directly, no. OG tags are for social sharing, not search engine ranking. However, they can indirectly help by increasing click-through rates when your links are shared, which can signal quality to search engines.
Can I use the same tags for Twitter?
Yes, but Twitter has its own set (twitter:card, twitter:title, etc.). If you don’t provide them, Twitter falls back to OG tags. It’s best to add both for full control over Twitter card appearance.
How often do social platforms re-fetch my page?
It varies. Facebook re-scrapes every 24 hours or when you force it via the debugger. LinkedIn is less predictable. Always use the platform’s debugging tool to force a fresh scrape after updating tags.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Stop Outlook From Changing Hyperlink Font
- Hiberfil.sys: What It Is & How to Delete It
- How to Make a Mask on Snapchat: Step-by-Step
- How to Factory Reset iPad If You Forgot Password
- Ubuntu in Windows Store: Which Editions Work?
- Secure Guest Account on Windows 11: Step-by-Step