Angular 组件条件仅在页面重新加载时显示
Angular component condition only show when page is reloaded
在我的 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) {}
这在页面第一次加载时有效,但当我转到另一条路线然后返回主路线时它不会加载,所以我必须重新加载页面才能显示组件。
我该如何解决这个问题?
您可以每次检查激活的路线。
import { ActivatedRoute } from '@angular/router';
constructor(public activatedRoute: ActivatedRoute) {
this.activatedRoute.url.subscribe(res => {
// array of route parts here
});
}
在我的 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) {}
这在页面第一次加载时有效,但当我转到另一条路线然后返回主路线时它不会加载,所以我必须重新加载页面才能显示组件。
我该如何解决这个问题?
您可以每次检查激活的路线。
import { ActivatedRoute } from '@angular/router';
constructor(public activatedRoute: ActivatedRoute) {
this.activatedRoute.url.subscribe(res => {
// array of route parts here
});
}