angular - 特定组件 Angular 的动态标题

标签 angular angular-routing

我正在使用 Angular 8 和 Java Spring 服务器端。现在这是我的路由

{ 
  component: IndexComp
  path: "index"
},
{ 
  component: BlogComp
  path: "blog"
},
{ 
  component: ProductComp
  path: "product/:id"
},

默认标题为“Shop”,用于博客和索引页面。但在产品页面中,标题来自服务器(可能是Iphone7、Iphone8、Skirt...取决于服务器的数据)。我想知道如何更改产品页面中的标题,谢谢

最佳答案

查看来自 @angular/platform-b​​rowserTitle

您可以将其注入(inject)组件中并使用 setTitle('You title string here')

例如:

  constructor(private readonly titleService: Title) {
    const title = 'Shop'; // get title data from the server
    this.titleService.setTitle(title);
  }

UPD:基于此,您可以将其放在任何您想要的地方:在解析器/组件/服务等中。


UPD:根据路线:例如,您可以像AppComponent中那样制作

  constructor(private readonly titleService: Title,
              private readonly router: Router) {
    this.router.events.subscribe(route => {
      if (route instanceof NavigationEnd && route.urlAfterRedirects !== '/product') {
        const title = 'Dynamic Title String Here';
        this.titleService.setTitle(title);
      } else {
        const title = 'Default Title String Here';
        this.titleService.setTitle(title);
      }
    });
  }

关于angular - 特定组件 Angular 的动态标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62534378/

相关文章:

angular - 在 Angular 上的延迟加载模块中嵌套子级

HTML5 音频在 Chrome 中达到其持续时间之前会自动停止

angular - 在 Angular 中保存/恢复路由器状态

angular - Angular 6 中的 HTTP 错误处理

angular - 子路由中的参数

Angular2 指令 - 字符串问题

javascript - 'this' 绑定(bind)到订阅函数而不是 Angular2 中的外部组件范围

html - 如何取消选中 Angular 7 中单击按钮时的复选框

angular-routing - 您可以在父路由器 socket 中显示您的子路由吗?

namespaces - 角达特 : Namespace of route names hierarchical too?