skip to Main Content

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

2

Answers


  1. There’s a npm module ng2-metadata [https://www.npmjs.com/package/ng2-metadata%5D
    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) { }
    
    Login or Signup to reply.
  2. As the author ng2-metadata and @ngx-meta/core projects, I’d suggest you to have a look at the package description (README file), as README files contain up-to-date information in most cases.

    There’s a depreciation warning on the npm page of ng2-metadata, saying that the project is deprecated, no longer maintained and now continues at @ngx-meta/core.

    If you switch using @ngx-meta/core, you’ll notice that the current issues you described here have already been resolved.

    About @ngx-meta/core: @ngx-meta/core is the successor of ng2-metadata, and the actual releases are v0.4.x and v0.2.x.

    If you’re using @angular v4.x.x, use the latest release of v0.4.x ([master] branch).

    The latest release for Angular 4 is v0.4.0-rc.1 as of now.

    If you’re using @angular v2.x.x, use the latest release of v0.2.x ([v0.2.x] branch).

    The latest release for Angular 2 is v0.2.0-rc.5 as of now.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search