angularmeta-tagsangular-universal

How to solve dynamic meta tags in Angular ssr?


I have an angular application with server side rendering. I am loading the meta tags content dynamicaly from backend. However in the html i see the meta tags with the proper content, the facebook debugger cant recognize the tags. Somebody faced with this issue?

I tried fill the meta tags in the component onInit func and fill the tags in a resolver.


Solution

  • create service RoutMetaService

     export class RoutMetaService {
     constructor(private title: Title, private meta: Meta) {}
    
    updateTitle(title: string) {
    this.title.setTitle(title);
     }
    
    updateOgUrl(url: string) {
    this.meta.updateTag({ name: 'og:url', content: url });
    console.log('updateOgUrl');
    }
    
    updateDescription(desc: string) {
    this.meta.updateTag({ name: 'description', content: desc });
     }
    updateKeywords(key: string) {
    this.meta.updateTag({ name: 'keywords', content: key });
     }
    }
    

    in routing.module.ts

          {
        path: "path name",
        component: Your Component,
        data: {
          title: "Title Page",
          description: "Description Meta Tag Content",
          ogUrl: "your og url",
          keywords: " Keywords Meta Tag Content ",
        },
      },
    

    In your typescript components constructor

    constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private routMeta: RoutMetaService
     ) {}
    
    
      ngOnInit() {
    this.router.events
      .pipe(
        filter((event: any) => event instanceof NavigationEnd),
        map(() => this.activatedRoute),
        map((route) => {
          while (route.firstChild) route = route.firstChild;
          return route;
        }),
        filter((route) => route.outlet === "primary"),
        mergeMap((route) => route.data)
      )
      .subscribe((event: any) => {
       //Updating Description tag dynamically with title
        this.routMeta.updateTitle(event["title"]);
        //Updating Description tag dynamically with ogUrl
        this.routMeta.updateOgUrl(event["ogUrl"]);
         //Updating Description tag dynamically with description
        this.routMeta.updateDescription(event["description"]);
        //Updating Description tag dynamically with keywords
        this.routMeta.updateKeywords(event["keywords"]);
        });
      }
    

    in index.html

     <title>title</title>
      <meta name="description" content="">
      <meta name="keywords" content="">