5

I need to take page title and write it to a variable. I am using typescript code:

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

@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {

    title: string;

    ngOnInit() {
        console.log("Title is " + this.title);
        this.title === document.title;
    }
}

But I am getting "Title is undefined" on a console.

I also tried:

 title: string;

    ngOnInit() {
        this.title === this.titleService.getTitle();
        console.log("Title is " + this.title);
    }
    public constructor(private titleService: Title) { }
    getTitle() {
        this.titleService.getTitle();
    }

but the result is the same. What is the correct way to get page title?

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
kendzi
  • 311
  • 2
  • 6
  • 22

2 Answers2

2

You have made several mistakes.

  1. === is used for Strict Equality Comparison, not for setting a value of a variable (more about === operator can be found here: Difference between == and === in JavaScript).
  2. You are first display variable, and after that trying to "set" (look at point 1) its value.

Change your code to:

 ngOnInit() {
      this.title = document.title
      console.log(this.title)
 }

or:

ngOnInit() {
    this.title = this.titleService.getTitle();
    console.log("Title is " + this.title);
}
Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
  • This look great but i got An unhandled exception occurred while processing the request. Exception: Call to Node module failed with error: Error: Uncaught (in promise): ReferenceError: document is not defined ReferenceError: document is not defined How should i define it? – kendzi Jul 20 '17 at 21:05
  • What about second approach? With `titleService` ? – Maciej Treder Jul 20 '17 at 21:06
  • To be honest I am surprised, that the first one did not. On my end, it is working without any problems. – Maciej Treder Jul 20 '17 at 21:10
0

You can use Title provider from @angular/platform-browser. Refer to https://medium.com/@_ericmiller/setting-the-title-in-angular2-3c9379090527

RKG
  • 592
  • 1
  • 7
  • 23