Search code examples
angularwebpackangular-clireflect-metadata

In angular cli how can you add meta data to routes e.g. title and description tags


In angular cli how can you add meta data to routes e.g. title and description tags?

These are my routes:

import { Route} from '@angular/router';
import { HomeComponent } from './home.component';

export const HomeRoutes: Route[] = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'home',
    component: HomeComponent
  }
];

I want to add title and description to these routes so that they are seen in the browser e.g. title for each route.

Furthermore, I would like them to be picked up by bots e.g. google seo bots.

I'm using angular cli with webpack, angular version 4, and typescript.

Current Error:

enter image description here


Solution

  • There's a npm module ng2-metadata [https://www.npmjs.com/package/ng2-metadata] it will serve the need.

    Sample Code.

    export const routes = [
      {
        path: 'home',
        component: HomeComponent,
        data: {
          metadata: {
            title: 'Sweet home',
            description: 'Home, home sweet home... and what?'
          }
        }
      },
      {
        path: 'duck',
        component: DuckComponent,
        data: {
          metadata: {
            title: 'Rubber duckie',
            description: 'Have you seen my rubber duckie?'
          }
        }
      },
      {
        path: 'toothpaste',
        component: ToothpasteComponent,
        data: {
          metadata: {
            title: 'Toothpaste',
            override: true, // prevents appending/prepending the application name to the title attribute
            description: 'Eating toothpaste is considered to be too healthy!'
          }
        }
      }
      ...
    ];
    

    Add this in app.module.ts

     imports: [
        ...
        RouterModule.forRoot(routes),
        MetadataModule.forRoot()
      ],
    

    And inject it in component constructor.

      constructor(private metadataService: MetadataService) { }