sodcalculator

10 Tech How-To

Add Open Graph Tags to an Angular App

Guide 10-56171 · Updated · Step by step

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

  1. Create a service for managing meta tags. Run ng generate service services/og-tags in your terminal. This creates a service file where you’ll centralize all Open Graph logic.
  2. Inject Angular’s Meta and Title services. Open the generated og-tags.service.ts and add Meta and Title from @angular/platform-browser to the constructor:
  3. 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) {}
    }
  4. Define a method that sets all OG tags. Add a public method, e.g., setOgTags(config: OgConfig), where OgConfig is an interface with optional title, description, image, and url fields. Inside, use this.title.setTitle() for the browser tab and this.meta.updateTag() for each OG property.
  5. Update or add each OG tag. For every property you want to set, call updateTag with the attribute selector. Example: this.meta.updateTag({ property: 'og:title', content: config.title }). Repeat for og:description, og:image, og:url, and og:type (usually ‘website’ or ‘article’).
  6. 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’s ngOnInit so every page has at least basic tags before route-specific ones apply.
  7. Set tags on each route change. In your main AppComponent or a dedicated component, subscribe to Router.events. Filter for NavigationEnd events, then map the current URL to your route data. You can attach OG values to each route’s data property in your router config:
  8. {
      path: 'product/:id',
      component: ProductComponent,
      data: {
        ogTitle: 'Product Page',
        ogDescription: 'View this product'
      }
    }
  9. 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’s setOgTags method. For dynamic values like a product name, fetch the data in the component itself and call the service after the data arrives.
  10. Handle dynamic content. For pages that load data asynchronously (e.g., from an API), call ogTagsService.setOgTags(...) inside the subscribe callback of your HTTP request, after you have the real title and description.
  11. Add Twitter Card tags (optional). Twitter uses its own tags if present. Add twitter:card, twitter:title, twitter:description, and twitter:image using the same updateTag method but with name instead of property.
  12. 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.
  13. 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_ANYTHING to the URL being scraped to bust the cache.

Common Mistakes

  • Forgetting to update the og:url tag. If your app uses client-side routing, the URL in the OG tag must match the actual shared URL. Use window.location.href or the router’s current URL.
  • Using addTag instead of updateTag. addTag creates duplicate tags if called multiple times. updateTag finds an existing tag and replaces its content, or creates it if missing.
  • Setting tags only in the component. If the component’s ngOnInit runs 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.png will 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 Meta service for all meta tags. It also handles standard meta tags like description and keywords, 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:locale tag. If your app supports multiple languages, add og:locale and og:locale:alternate to 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_ANYTHING to 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:title tags, you’re likely calling addTag instead of updateTag, or the service is instantiated multiple times. Use updateTag consistently 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

The whole Tech How-To bed →