ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Dynamic Meta Tags in Angular

In this tutorial, we learn how to add Dynamic Meta Tags in Angular. First, we will define the Meta Tags in the Angular Routes. Then use the Meta Service and NavigationEnd router event to listen to the route change. When the route changes, we will update the Meta Tags.

Meta Tags

We use the Meta Service in Angular to add/remove meta tags. It provides the following methods

  1. addTag()
  2. addTags()
  3. getTag()
  4. getTags()
  5. updateTag
  6. removeTag
  7. removeTagElement

To use Meta Service, we first need to import it root module and inject it in Angular Providers as shown below

                              

import { BrowserModule, Meta } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [Meta],
  bootstrap: [AppComponent]
})
export class AppModule { }
 
                            
                        

And in the component class, first, inject the Meta Service using Angular Dependency Injection. Use any of the methods of the Meta Service to manipulate the Tags.

                              

import { Component, OnInit } from '@angular/core';
import { Meta, MetaDefinition } from '@angular/platform-browser';
 
@Component({
  template: `<h1>First Component</h1>`
})
export class FirstComponent {
 
  constructor(private metaService: Meta) {
    this.addTag();
  }
 
  addTag() {
    this.metaService.addTag({ name: 'description', content: 'Article Description' });
    this.metaService.addTag({ name: 'robots', content: 'index,follow' });
    this.metaService.addTag({ property: 'og:title', content: 'Content Title for social media' });
  }
 
}
                            
                        

Dynamic Meta Tags

Adding Meta tags in component class is little inconvenient. The better way is to define all the meta tags at a central place preferably when we define the routes. Whenever the route changes, we can read the Tags from the router and update Mega tags.

Example App

Create a new Angular Application. Add HomeComponent, FirstComponent, SecondComponent, SecondAComponent & ThirdComponent as shown below.

home.component.ts
                              

import { Component, OnInit } from '@angular/core';
import { Meta, MetaDefinition } from '@angular/platform-browser';
 
@Component({
  template: `<h1>Home Component</h1>`
})
export class HomeComponent {
}
 
                            
                        
first.component.ts
                              
 
import { Component, OnInit } from '@angular/core';
import { Meta, MetaDefinition } from '@angular/platform-browser';
 
@Component({
  template: `<h1>First Component</h1>`
})
export class FirstComponent {
}
 
                            
                        
second.component.ts
                              

import { Component, OnInit } from '@angular/core';
import { Meta, MetaDefinition } from '@angular/platform-browser';
 
@Component({
  template: `<h1>Second Component</h1>`
})
export class SecondComponent {
}
 
                            
                        
secondA.component.ts
                              

import { Component, OnInit } from '@angular/core';
import { Meta, MetaDefinition } from '@angular/platform-browser';
 
@Component({
  template: `<h1>Second A Component</h1>`
})
export class SecondAComponent {
}
                            
                        
third.component.ts
                              
 
import { Component, OnInit } from '@angular/core';
import { Meta, MetaDefinition } from '@angular/platform-browser';
 
@Component({
  template: `<h1>Third Component</h1>`
})
export class ThirdComponent {
}
                            
                        

Meta Tags in Route

The next step is to add the Meta tags in the route

Open the app-routing.module.ts and the routes as shown below. Add the Meta Tags property in route data. We can use the Route data to pass the static data or dynamic data to routed components. The title is also added to the Route Data.

                              
 
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FirstComponent } from './first.component';
import { SecondComponent } from './second.component';
import { SecondAComponent } from './secondA.component';
import { ThirdComponent } from './third.component';
import { HomeComponent } from './home.component';
 
 
const routes: Routes = [
  {
    path: '', component: HomeComponent, pathMatch: 'full',
    data: {
      title: 'Title for Home Component',
      descrption: 'Description of Home Component',
      ogTitle: 'Description of Home Component for social media',
    }
  },
  {
    path: 'first', component: FirstComponent,
    data: {
      title: 'Title for First Component',
      descrption: 'Description of First Component',
      robots: 'noindex, nofollow',
      ogTitle: 'Description of First Component for social media',
    }
  },
  {
    path: 'second', children:
      [
        {
          path: '', component: SecondComponent, pathMatch: 'full',
          data: {
            title: 'Title for Second Component',
            descrption: 'Description of Second Component',
          }
        },
        {
          path: 'a', component: SecondAComponent,
          data: {
            title: 'Title for Second A Component',
            descrption: 'Description of Second A Component',
            ogTitle: 'Title of Second A Component for social media',
            ogDescription: 'Description of Second A Component for social media',
            ogImage: 'ImagePathForSocialMedia'
          }
        },
      ]
  },
  {
    path: 'third', component: ThirdComponent,
    data: {
      title: 'Title for third Component',
      descrption: 'Description of third Component',
      ogDescription: 'Description of third Component for social media',
      ogUrl: '/home'
    }
  },
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
 
                            
                        

Listen to Navigation Changes

Whenever a user navigates to a new route (or page), the router fires the navigation events. The Router raises the NavigationEnd event, when it successfully completes the navigation.

We must listen to every NavigationEnd event and the best place to listen is in our root component. i.e. app.component.ts. The code is as shown below.

                              

import { Component, OnInit } from '@angular/core';
import { Title, Meta } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { filter, map } from 'rxjs/operators';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 
  constructor(private router: Router,
    private activatedRoute: ActivatedRoute,
    private titleService: Title,
    private metaService: Meta) {
  }
 
  ngOnInit() {
 
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
    )
      .subscribe(() => {
 
        var rt = this.getChild(this.activatedRoute)
 
        rt.data.subscribe(data => {
          console.log(data);
          this.titleService.setTitle(data.title)
 
          if (data.descrption) {
            this.metaService.updateTag({ name: 'description', content: data.descrption })
          } else {
            this.metaService.removeTag("name='description'")
          }
 
          if (data.robots) {
            this.metaService.updateTag({ name: 'robots', content: data.robots })
          } else {
            this.metaService.updateTag({ name: 'robots', content: "follow,index" })
          }
 
          if (data.ogUrl) {
            this.metaService.updateTag({ property: 'og:url', content: data.ogUrl })
          } else {
            this.metaService.updateTag({ property: 'og:url', content: this.router.url })
          }
 
          if (data.ogTitle) {
            this.metaService.updateTag({ property: 'og:title', content: data.ogTitle })
          } else {
            this.metaService.removeTag("property='og:title'")
          }
 
          if (data.ogDescription) {
            this.metaService.updateTag({ property: 'og:description', content: data.ogDescription })
          } else {
            this.metaService.removeTag("property='og:description'")
          }
 
          if (data.ogImage) {
            this.metaService.updateTag({ property: 'og:image', content: data.ogImage })
          } else {
            this.metaService.removeTag("property='og:image'")
          }
 
 
        })
 
      })
 
  }
 
  getChild(activatedRoute: ActivatedRoute) {
    if (activatedRoute.firstChild) {
      return this.getChild(activatedRoute.firstChild);
    } else {
      return activatedRoute;
    }
 
  }
}
 
                            
                        

The following code subscribes to the router change event. The filter RxJS Operator filters out NavigationEnd event. We subscribe to it.

                              

    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
    )
      .subscribe(() => {
                            
                        

In the next line, we recursively traverse through the ActivatedRoute tree to get to the current route.

                              

var rt = this.getChild(this.activatedRoute)
                            
                        

Once we have the ActivateRoute of the currently loaded component, we subscribe to the data property to read the Route Data.

                              

      rt.data.subscribe(data => {
          console.log(data);
 
                            
                        

Now, we can set the title using title service

                              

this.titleService.setTitle(data.title)
 
                            
                        

Update the Meta Description if one is defined on the route. Else we can remove the description set for the previous component.

                              

          if (data.descrption) {
            this.metaService.updateTag({ name: 'description', content: data.descrption })
          } else {
            this.metaService.removeTag("name='description'")
          }
 
                            
                        

In cases like robots tag, it is better to set it to follow,index as a default, if not tags were not defined.

                              

         if (data.robots) {
            this.metaService.updateTag({ name: 'robots', content: data.robots })
          } else {
            this.metaService.updateTag({ name: 'robots', content: "follow,index" })
          }
 
                            
                        
app.component.html
                              

<h1>Angular Dynamic Meta Tags Example</h1>
 
<ul>
  <li><a [routerLink]="['/']">Home</a> </li>
  <li><a [routerLink]="['/first']">First</a> </li>
  <li><a [routerLink]="['/second']">Second</a> </li>
  <ul>
    <li><a [routerLink]="['/second/a']">Second A</a> </li>
  </ul>
  <li><a [routerLink]="['/third']">third</a> </li>
</ul>
 
<router-outlet></router-outlet>
                            
                        
app.module.ts
                              

import { BrowserModule, Meta } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FirstComponent } from './first.component';
import { SecondAComponent } from './secondA.component';
import { ThirdComponent } from './third.component';
import { SecondComponent } from './second.component';
import { HomeComponent } from './home.component';
 
@NgModule({
  declarations: [
    AppComponent, FirstComponent,SecondAComponent, ThirdComponent, SecondComponent, HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [Meta],
  bootstrap: [AppComponent]
})
export class AppModule { }
 
                            
                        
image

Angular Dynamic Meta Service