ng 设置动态的document title

  1. 配置路由, 添加data.title参数
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    component: DashComponent,
    data: {
      title: 'Examples',
    },
  },
  {
    path: 'enumerate-devices',
    component: EnumerateDevicesComponent,
    data: {
      title: '查看 video audio 设备列表',
    },
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}
  1. 监听路由导航完毕,读取data.title,设置document.title
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'live-video-example-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.styl'],
})
export class AppComponent implements OnInit {
  constructor(
    private readonly titleService: Title,
    private route: ActivatedRoute,
    private readonly router: Router
  ) {}

  ngOnInit() {
    this.router.events.subscribe((e) => {
      if (e instanceof NavigationEnd) {
        let child = this.route.firstChild;
        while (child.firstChild) {
          child = child.firstChild;
        }
        const title = child.snapshot.data['title'];
        this.titleService.setTitle(title ?? 'ng app');
      }
    });
  }
}
原文地址:https://www.cnblogs.com/ajanuw/p/12715004.html