【问题标题】:Angular component condition only show when page is reloadedAngular 组件条件仅在页面重新加载时显示
【发布时间】:2019-03-10 19:49:49
【问题描述】:

在我的 app.component.html 上,如果我在某个路线上,我有一个条件来显示一个组件:

app.component.html

<div *ngIf="router.url === '/home'">
  <app-slider></app-slider>
</div>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
...
constructor(public router: Router) {}

这在页面第一次加载时有效,但是当我转到另一条路线然后返回主路线时它不会加载,因此我必须重新加载页面才能显示组件。

我该如何解决这个问题?

【问题讨论】:

  • 你能解释一下你的要求吗
  • 基本上 仅在我在家庭路由器中时出现,但是当我导航到另一条路线然后单击家庭路由器时,条件不起作用。如果仅在我重新加载页面时有效

标签: angular angular-routing angular7


【解决方案1】:

您可以每次检查激活的路线。

import { ActivatedRoute } from '@angular/router';
constructor(public activatedRoute: ActivatedRoute) {
    this.activatedRoute.url.subscribe(res => {
    // array of route parts here
    });
}

【讨论】:

  • 你的意思是://这里的路线部分数组?
  • console.log(res);请检查输出。
  • 链接到文档可能会更有帮助,因为这样@KevinPorche 将能够研究 res 是 UrlSegment[] angular.io/api/router/ActivatedRoute#activatedroute 类型的可观察对象
  • 返回这个:0: UrlSegment parameterMap: (...) parameters: {} path: ""
  • @KevinPorche 您可以在回复时尝试toString()。这将为您提供字符串格式的路线。像这样:res.toString() 。这是链接angular.io/api/router/UrlSegment
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2023-01-29
  • 2021-06-29
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
相关资源
最近更新 更多