【问题标题】:Angular 2 routing hide selector when navigate导航时Angular 2路由隐藏选择器
【发布时间】:2017-12-03 11:06:28
【问题描述】:

在我的应用程序组件 html 中,我有一个选择器和路由器插座。当我尝试通过单击链接进行导航时,选择器仍然存在。如何隐藏选择器?只有路由器插座应该显示。

app.component.html

<nav>
<a [routerLink]="['/heroes']">Click here</a>
</nav>

<router-outlet></router-outlet> <--  Display the content here 

<feed></feed> <--- feed component selector

app.component.ts

import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/map';

@Component({
selector: "app",
templateUrl: "app/app.component.html"
})
export class AppComponent implements OnInit {

ngOnInit() {
}}

app.routing.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroComponent } from "./components/hero/hero.component";
const routes: Routes = [
{ path: 'heroes', component: HeroComponent}
];

@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }

export const routingComponents = [HeroComponent];

索引.html

<app>Loading...</app>

如何做到这一点?

【问题讨论】:

    标签: javascript angularjs typescript routing


    【解决方案1】:

    取决于你的目标,你想在路由改变时从 dom 中删除所有内容吗?

    如果是,您应该将router-outlet 放在您的应用组件中。

    现在它的行为符合预期,角度正在呈现HeroComponent 的视图内容在router-outlet 标记内保留页面中的任何“额外”标记

    如果您只想从视图中删除提要组件,您可以这样做:

     //take a reference to the current active route
     constructor(private route:ActivatedRoute) {
       this.activeRoute = route.snapshot.url;
    
     }
    
    <feed *ngIf="activeRoute !== '/heroes''"></feed>
    

    【讨论】:

    • 我也可以使用 *ngIf="router.url.includes('/')" 这样的东西,它应该只呈现提要组件,只有当你在主页或根页面时..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多