ANGULAR2: set Page-Title dynamically AS ANGULAR SERVICE IN ANGULAR 2 APPLICATION

Standard

Since page-title is essential component for any web application.

Usage

Since page-title is used throughout the application, so its better to define it once in index.html and then try to set/reset through component code. I am also using BehaviorSubject object in service, which is way more awesome and better then observable in many cases, Behavior Subject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. In plain words when specific page is invoked, its ngOnit() method call the page-title service and pass the reference of page-title value to be load, then service set new value into its BehaviorSubject object(title), all variables(header) throughout the application subscribed to this BehaviorSubject object are then alerted and refresh their state with the new value.

Index/main-component.html code:

<a class="navbar-brand" href="#">{{header}}</a>

main-component.ts:

import { Component, OnInit} from '@angular/core';

import { PageTitleService } from './shared/service/page-title.service';

@Component({
    selector: 'my-app',
    templateUrl: '../../Scripts/app/app.component.html'
})

export class AppComponent implements OnInit {
    header: string;

    constructor(
        private pageTitleService: PageTitleService) {
    }

    ngOnInit() {

        this.pageTitleService.title.subscribe((val: string) => {
            this.header = val;
        });
    }
}

pageTitle.service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class PageTitleService {
    public title: BehaviorSubject<string> = new BehaviorSubject<string>(null);

    setTitle(value: string) {
        this.title.next(value);
    }
}

custom-component.ts:

import { Component, OnInit } from '@angular/core';

import { PageTitleService } from '../../shared/service/page-title.service';

@Component({
    selector: 'search-movie-detail',
    templateUrl: '../../Scripts/app/search-movies/detail.component.html'
})

export class SearchMovieDetailComponent implements OnInit {

    constructor(
        private pageTitleService: PageTitleService) {
        
    }

    ngOnInit() {
        this.pageTitleService.setTitle("Movie Detail");
    }

}

Output:

screenshot_12

screenshot_10 screenshot_11