组件不会在Angular 9的子路径中渲染

时间:2020-04-26 12:16:52

标签: angular angular-material angular-material2 angular9

这是我的app.component.html

<app-sidenav></app-sidenav>

sidenav.component.html

<mat-sidenav-container class="some-class">
    <mat-sidenav opened mode="side">
        ...
    </mat-sidenav>
    <mat-sidenav-content>
        <router-outlet></router-outlet>
    </mat-sidenav-content>
</mat-sidenav-container>

app-routing.module.ts

const routes: Routes = [

  { path: '', redirectTo: '/home', pathMatch: 'full', },
  { path: 'home', component: HomeComponent, },
  { path: 'admin', redirectTo: '/admin/users', pathMatch: 'full', },
  { path: 'admin', children: [{
      path: 'permissions', component: PermissionsComponent, }, {
      path: 'users', component: UsersComponent, },]},
];

和路由组成部分之一是UsersComponent,并具有以下模板:

<mat-toolbar>
  <h1 class="headline">Administration</h1>
</mat-toolbar>

<mat-sidenav-container>
  <mat-sidenav opened mode="side">
    ...
  </mat-sidenav>
  <mat-sidenav-content>
    <p>users works!</p>
  </mat-sidenav-content>
</mat-sidenav-container>

,直到现在为止,它都按预期工作。但是,当我创建一个新组件(例如,inner-sidenav和以下模板(来自UsersComponent)时:

<mat-sidenav opened mode="side">
  ...
</mat-sidenav>

并将UsersComponent的模板更新为:

<mat-toolbar>
  <h1 class="headline">Administration</h1>
</mat-toolbar>

<mat-sidenav-container>
    <app-inner-sidenav></app-inner-sidenav>
  <mat-sidenav-content>
    <p>users works!</p>
  </mat-sidenav-content>
</mat-sidenav-container>

内部mat-sidenav(应代替app-inner-sidebar渲染)根本不渲染。我想念什么?

更新

要复制该问题,请访问here

2 个答案:

答案 0 :(得分:0)

@Hasan原因是Material Sidenav的嵌套规则。 您不能将“ foreign”元素作为<mat-sidenav-container>的直接子代(很像<table>只能将<thead>, <tbody>, <tr>作为直接子代)。

相反,用户组件标记应为:

<mat-sidenav-container>
    <mat-sidenav opened mode="side">
      <app-inner-sidenav></app-inner-sidenav>
    </mat-sidenav>
  <mat-sidenav-content>
    <p>users works!</p>
  </mat-sidenav-content>
</mat-sidenav-container>

内部导航栏组件的标记应为:

<a [routerLink]="['/admin/users']">Users</a>

答案 1 :(得分:0)

<mat-sidenav-content>中有<mat-sidenav-container>时,就不能在<mat-sidenav-container>中添加自定义html。相反,您必须在<app-inner-sidenav>内添加<mat-sidenav-content>

<mat-sidenav-container>
  <mat-sidenav opened mode="side">
    <a [routerLink]="['/admin/users']">Users hehe</a>
  </mat-sidenav>
  <mat-sidenav-content>
    <app-inner-sidenav></app-inner-sidenav>
    <p>users works!</p>
  </mat-sidenav-content>
</mat-sidenav-container>

或者您可以像这样删除<mat-sidenav-content>

<mat-sidenav-container>
    <mat-sidenav opened mode="side">
        <a [routerLink]="['/admin/users']">Users hehe</a>
    </mat-sidenav>
    <app-inner-sidenav></app-inner-sidenav>
    <p>users works!</p>
</mat-sidenav-container>