how to change page title in angular2 router

后端 未结 14 1239
深忆病人
深忆病人 2020-12-04 16:17

I am trying to change the page title from the router, can this be done?

import {RouteConfig} from \'angular2/router\';
@RouteConfig([
  {path: \'/home\', com         


        
相关标签:
14条回答
  • 2020-12-04 17:10

    Its really very easy to do this, you can follow therse steps to see the immediate effects:

    we provide the Title service in bootstrap:

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

    Then import this service in the component you want:

    import { Component } from '@angular/core';
    import { Title }     from '@angular/platform-browser';
    
    @Component({
    selector: 'my-app',
    template:
      `<p>
        Select a title to set on the current HTML document:
      </p>
    
      <ul>
        <li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
        <li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
        <li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
      </ul>
      `
    })
    export class AppComponent {
      public constructor(private titleService: Title ) { }
    
      public setTitle( newTitle: string) {
        this.titleService.setTitle( newTitle );
      }
    }
    

    now click on those links to see the title changing.

    you can also use ng2-meta for changing page title and description as well,you can refer to this link:

    https://github.com/vinaygopinath/ng2-meta

    0 讨论(0)
  • 2020-12-04 17:13

    Angular 2 provides a Title Service see Shailesh answer is just copy of that code.

    I our app.module.ts

    import { BrowserModule, Title } from '@angular/platform-browser';
    ........
    providers: [..., Title],
    bootstrap: [AppComponent]
    

    Now move to our app.component.ts

    import { Title }     from '@angular/platform-browser';
    ......
    export class AppComponent {
    
        public constructor(private titleService: Title ) { }
    
        public setTitle( newTitle: string) {
          this.titleService.setTitle( newTitle );
        }
    }
    

    Put the title tag on your component html and it will read and set for you.

    If you want to know how to set it dynamically and further detail see this article

    0 讨论(0)
提交回复
热议问题