Smo*_*son 13 javascript typescript angular
嗨,我不知道这是否可能...基本上我希望能够显示一个组件,但只有当路线匹配并隐藏一个组件,如果路线匹配我已经尝试这app-header-home
显示当路线'/'
是好的,但app-header
没有显示甚至在路线时'/'
我怎么能解决这个问题呢?
app.component.html
<app-header *ngIf="router.url == '/'"><app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home> //component I want hidden unless url '/'
<router-outlet></router-outlet>
<app-footer></app-footer>
Run Code Online (Sandbox Code Playgroud)
app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
constructor(
private router: Router
) {
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
Sac*_*aka 17
检查router.url
模板中:
<app-header><app-header>
<app-header-home *ngIf="router != '/ur_route'"></app-header-home> //component I want hidden unless url /home
<router-outlet></router-outlet>
<app-footer></app-footer>
Run Code Online (Sandbox Code Playgroud)
在app.component.ts
注入router
.
export class AppComponent {
title = 'app';
router: string;
constructor(private _router: Router){
this.router = _router.url;
}
}
Run Code Online (Sandbox Code Playgroud)
Cht*_*lek 13
接受的答案不起作用,因为我认为变量只会被分配一次,然后当我们导航时,该变量不会更新(组件已经初始化)。
我是这样做的..我们将路由器注入到我们想要隐藏的组件中:
constructor(private _router: Router){}
Run Code Online (Sandbox Code Playgroud)
然后在我们的模板中:
<div *ngIf="_router.url != '/login'">
... your component html ...
</div>
Run Code Online (Sandbox Code Playgroud)
这是参考 发表的评论SUNIL JADHAV
。我们可以在函数中定义它并在模板中调用它,而不是在模板上公开路由器句柄。
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
constructor(
private router: Router,
) {}
ngOnInit() {
}
/**
* Check if the router url contains the specified route
*
* @param {string} route
* @returns
* @memberof MyComponent
*/
hasRoute(route: string) {
return this.router.url.includes(route);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在 html 文件中我们可以像这样使用它
<!-- First view -->
<div *ngIf="hasRoute('home')">
First View
</div>
<!-- Second view activated when the route doesn't contain the home route -->
<div *ngIf="!hasRoute('home')">
Second View
</div>
Run Code Online (Sandbox Code Playgroud)