Angular 4 - 逐页更新标题

时间:2018-03-22 12:34:07

标签: angular

在" src"中的index.html中文件夹,我写了{{title}},如下所示:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{{ title }}</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>

在product.components.ts中,我将标题定义为&#34;产品&#34;如下,但它不会起作用。

export class ProductComponent implements OnInit {
  products: Product[] = [];
  dataInvalid = false;
  formErrors = [];
  formSubmitting = false;
  title = 'Products';

如果用户点击不同的网页,如何更改标题?

3 个答案:

答案 0 :(得分:2)

您必须从组件中的platform-b​​rowser注入Title

import {Title} from "@angular/platform-browser";

constructor(private title: Title) {
            this.title.setTitle('Your title');
}

答案 1 :(得分:1)

只需添加到路由中。所以你不需要在每个组件中注入标题服务。对于Ex

 path: ':path',
 component: ExampleComponent,
 data: {title:'title'}

答案 2 :(得分:0)

现在您可以使用anglar设置标题标记和元标记。 只需将提供的服务用于@angular/platform-browser 我们走了......

import { Title, Meta }     from '@angular/platform-browser';

@Component({
selector: 'app-root',
template:
  `My component
  `
})
export class YourComponent {
  public constructor(private titleService: Title, private meta: Meta ) {
     this.setTitle('My title');
     this.setDynamicTitle();
     this.setMetaTags()
  }

  public setTitle( newTitle: string) {
    // each component
    this.titleService.setTitle( newTitle ); 
  }
  public setDynamicTitle() {
     // via service
    this.yourService.get('api/url').subscribe((data) => {
       this.titleService.setTitle( data.title );  
    })
  }
  public setMetaTags() {
      this.meta.addTags([{
          name: 'description',
          content: 'Your description'
        }, {
          name: 'author',
          content: 'You'
        }
      ])
  }
}

这里有另一个参考:How to change title of a page using angular(angular 2 or 4) route?