0

我有一个具有 HomeComponent 的应用程序,我不想在其中显示 HeaderComponent。此外,我还有其他 4 条路线,我确实想要渲染标题。我可以让它工作,但是当我从 HomeComponent 导航到任何其他组件时有一个小错误。它不会呈现 HeaderComponent,但是当我在导航器上重新加载页面时,它会正确显示标题。我尝试了很多东西,但仍然无法使其正常工作......

我想要 在所有路由上显示 HeaderComponent,除了 /home (HomeComponent)。

这是我的代码 app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { ContactoComponent } from './contacto/contacto.component';
import { HomeComponent } from './home/home.component';
import { PortfolioComponent } from './portfolio/portfolio.component';
import { SkillsComponent } from './skills/skills.component';

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
  },
  { path: 'about', component: AboutComponent, data: { animation: 'fader' } },
  {
    path: 'contacto',
    component: ContactoComponent,
    data: { animation: 'fader' },
  },
  { path: '**', redirectTo: '' },
];

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

应用模块.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HeaderComponent } from './header/header.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { CvComponent } from './cv/cv.component';
import { ContactoComponent } from './contacto/contacto.component';


@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    HomeComponent,
    AboutComponent,
    ContactoComponent,
    CvComponent,
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    NgbModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

app.component.html

<app-header *ngIf="router.url !== '/home'"></app-header>
<router-outlet> </router-outlet>

我还尝试<app-header></app-header>在每个模板上调用“about.component.html”和“contacto.component.html”,但结果相同......

我想这是试图显示 HeaderComponent,但在我重新加载页面之前它不存在。请你能帮帮我吗……?

4

1 回答 1

1

您可以创建一个布局组件并将您的其他页面加载为布局组件内的子路由,并将标题放在布局组件内。

const routes: Routes = [
{path:'home':component : homecomponent}
{
 path: ' ',
 component: HeaderOnlyLayoutComponent,
 children: [
  { path: 'youotherpath', component: 
   childcomponent },
  ]
  }
]

您可以在此处查看完整的描述和示例 链接

于 2021-12-18T22:54:11.680 回答