Search code examples
angularangular6metaasp.net-boilerplate

How to add meta tag in index.html dynamically with data in angular?


I want to share some content in facebook with title, image and description. For that I need to add meta tag dynamically in index.html. I tried every possible aspects but it's not working. The description, image are not showing after sharing in facebook. I searched many solutions but didn't work for me. Is there anyone to help me to get rid of this issue ? thanx in advance


Solution

  • You can use the SEO services given by Angular: Title and Meta from @angular/platform-browser.

    First you will have to add some data to your routes, for example:

    const routes: Routes = [
      {
        path: '', component: AboutComponent,
        data: {
          title: 'About',
          metatags: {
            'og:description': `your description here`,
            'twitter:description': `your description`,
             keywords: `your keywords here`
          }
        }
      }
    ];
    

    Then inside your method ngOnInit of your app.component.ts file, you will track the router events and for each NavigationEnd event (means a new page is reached) you will update your tags and title following the data specified in your routes :

    ngOnInit() {
        // Change page title on navigation  based on route data
        this.router.events
          .pipe(
            filter(event => event instanceof NavigationEnd),
            map(() => {
              let route = this.activatedRoute;
              while (route.firstChild) {
                route = route.firstChild;
              }
              return route;
            }),
            filter(route => route.outlet === 'primary'),
            mergeMap(route => route.data)
          )
          .subscribe(event => {
            const title = event['title'];
            if (title) {
              const _title = `${environment.appName} | `;
              this.titleService.setTitle(_title);
              this.metaService.updateTag({ name: 'title', content: _title });
            }
    
            const tags = event['metatags'];
            if (tags) {
              for (const tag in tags) {
                this.metaService.updateTag({ property: tag, content: tags[tag] });
              }
            }
          });
      }
    
    

    But for some data loaded dynamically, example a specified product, you can add this code inside you page component product-details.component.ts :

     ngOnInit() {
        this.product$ = this.activatedRoute.data.pipe(
          switchMap((data) => this.activatedRoute.paramMap.pipe(
            // get the requested id in url to fetch the correct document
            switchMap((params) => this.productService.getProduct(params.get('id'))),
            tap((product: Product) => {
              const _title = `${environment.appName} | ${product.name}`;
              this.titleService.setTitle(_title);
              this.metaService.updateTag({ name: 'title', content: _title });
              this.metaService.updateTag({ name: 'description', content: product.description});
            }),
          )));
    
      }
    
    

    Et voilà.

    But you will probably need to add Angular Universal to your project because not all the search bots can analyse Single Page Application like Angular.