gpt4 book ai didi

没有导航栏的 Angular 2 路由

转载 作者:太空狗 更新时间:2023-10-29 18:02:21 24 4
gpt4 key购买 nike

关于 Angular2 路由的每个主题都有一个固定的导航栏

<nav>
<a [routerLink]="['/component-one']">Component One</a>
<a [routerLink]="['/component-two']">Component Two</a>
</nav>
<router-outlet></router-outlet>

所以基本上当单击组件一的链接时,该组件将呈现在 <nav></nav> 下方。

我需要的是当您单击组件一时,完整 View (整页)更改为组件一的 View (因此没有 <nav></nav> )

我试着把 <router-outlet>在一个单独的@Component

// view.component.ts    
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
selector: 'view',
template:`<router-outlet></router-outlet>`,
directives: [ROUTER_DIRECTIVES]
})

export class ViewComponent {

}

然后

// home.component.ts
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
selector: 'home',
template: `
<nav>
<a [routerLink]="['/component-one']">Component One</a>
<a [routerLink]="['/component-two']">Component Two</a>
</nav>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})

export class HomeComponent {

}

App 组件如下所示:

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

import { HomeComponent } from './containers/home.component';

@Component({
moduleId: module.id,
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<view></view>
<home></home>
`,
styleUrls: ['app.component.css'],
directives: [HomeComponent, ROUTER_DIRECTIVES]
})
export class AppComponent {
title = 'app works';
}

也试过把<home>里面<view>但什么都没有

总是得到同样的错误:

Error: Cannot find primary outlet to load 'OneComponent'

谁能帮我解决这个问题?谢谢!

编辑

// app.routes.ts
import { provideRouter, RouterConfig } from '@angular/router';

import { ViewComponent } from './containers/view.component';
import { HomeComponent } from './containers/home.component';
import { OneComponent } from './containers/one.component';
import { TwoComponent } from './containers/two.component';

const routes: RouterConfig = [
{
path: '',
redirectTo: '',
pathMatch: 'full'
},
{
path: '',
component: HomeComponent,
},
{
path: 'one',
component: OneComponent
},
{
path: 'two',
component: TwoComponent
}
];

export const appRouterProviders = [
provideRouter(routes)
];

最佳答案

将你的路由移动到自己的组件

<nav>
<a [routerLink]="['/component-one']">Component One</a>
<a [routerLink]="['/component-two']">Component Two</a>
</nav>

并将它们注入(inject)到您想要拥有它们的组件上,当您路由到该组件时,您将看到导航,而当您转到另一个组件时,它们将从那里移除。

<router-outlet></router-outlet> 之上或之下的所有内容 将在每个页面中可用

关于没有导航栏的 Angular 2 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38869175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com