在Angular中加载没有根组件的组件

时间:2019-01-24 07:48:00

标签: javascript angular

我开始学习angular6。我遇到一种情况,我想不使用页眉和页脚来显示带有不同html的页面。我已经添加了app.component.html文件:

<app-header></app-header>

<router-outlet></router-outlet>
<app-footer></app-footer>

现在我要加载组件而不使用根组件。

2 个答案:

答案 0 :(得分:0)

好吧,您必须创建一个路由器,这是一个示例:

在app.module.ts中,添加:

import { RouterModule, Routes } from '@angular/router';
const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
    // other imports here
  ],
  ...
})
export class AppModule { }

在app.component.html中,您有<router-outlet></router-outlet>,这里是通过路由器角度注入组件的地方,因此请删除页眉和页脚并将它们放入需要显示的页面(组件)中。

答案 1 :(得分:0)

我认为您可以为此使用“ ng-template”;

首先创建这样的路由模块;

const routes: Routes = [

    { 
    path: 'login',
    component: LoginComponent,
    data: { showRootComponents: false } 
    },
    { 
    path: 'home',
    component: HomeComponent,
    data: { showRootComponents: true } 
    }

]

export const AppRoutingModule = RouterModule.forRoot(routes);

并将其导入到您的AppModule中

@NgModule({
  declarations: [
    AppComponent,
  HomeComponent,
  LoginComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
    ReactiveFormsModule   
  ]
  bootstrap: [AppComponent]
})
export class AppModule { }

然后在您的根组件中;

withoutRootComponents:boolean

public constructor(private activatedRoute:ActivatedRoute) {
    this.withoutRootComponents = activatedRoute.snapshot.data['showRootComponents']);
}

和html;

<ng-template [ngIf]="!withoutRootComponents">
   <app-header></app-header>
   <router-outlet></router-outlet>
   <app-footer></app-footer>
</ng-template>

<ng-template [ngIf]="withoutRootComponents">
   <router-outlet></router-outlet>
</ng-template>