![](/img/trans.png)
[英]How do you display different navigation bars on different pages in angular 6?
[英]How to display different templates, like error pages, in the same Angular X app
是否以 Angular 8 方式更改同一应用程序中的模板?
例如,应用程序包含使用页眉、侧边栏、页脚构建的容器组件。 然后内容总是显示在容器内。
如果我想显示一个错误页面,其中包含重定向到其他页面的按钮,该怎么办。 我不想在容器内加载该页面,而是作为一个单独的页面/模板,具有不同的 body/html 样式等。
我知道这可以用innerHTML
来完成,这是个坏主意。 到目前为止,我已经实现了一些我对使用TemplateRef
不满意的东西,因为它只能部分工作。 错误页面的 body/html 标签样式不会被反映,除非没有被封装——这是另一个坏主意。
在app.component 中,我根据条件更改模板 - 这也不能很好地工作,因为条件是错误服务器响应,它是异步的。
<app-container *ngIf="!condition"></app-container>
<div *ngIf="condition">
<app-container *ngTemplateOutlet="wrapper.errorTemplate"></app-container>
<app-error #wrapper></app-error>
</div>
在error.component我有:
@ViewChild('errorTemplate', { static: true }) errorTemplate: TemplateRef<any>;
我上面所做的可能也可以通过在不使用TemplateRef
的情况下实现条件显示container.component children 来实现
完成这项工作的最佳做法是什么?
您可以进行多层路由:
根.component.html
<router-outlet></router-outlet>
root.routing.ts
export const RootRoutes: Routes = [
{ path: 'error', loadChildren: 'path/to/error/module#ErrorModule',
{ path: '', loadChildren: 'path/to/app/module#AppModule' },
{ path: '**', pathMatch: 'full', redirectTo: 'error/404' },
];
这意味着,你必须引导你的RootModule
和添加RootComponent
自举阵列,并更改标签在你index.html
到像<app-root></app-root>
。
如果 url 中的路径与“错误”不匹配, AppModule
那里加载AppModule
。
另一种方法是在加载错误页面时使用服务来隐藏页眉、侧边栏和页脚。
简单的例子:
@Injectable({ providedIn: 'root' })
export class ContainerService {
readonly isErrorPage$ = this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map((event: NavigationEnd) => event.urlAfterRedirects.startsWith('/error')),
shareReplay(1)
);
constructor(private router: Router) {}
}
您可以在AppContainer
使用AppContainer
:
@Component({ ... })
export class ContainerComponent {
readonly showContainerElements$ = this.cs.isErrorPage$.pipe(
map((isErrorPage) => !isErrorPage)
);
constructor(private cs: ContainerService) {}
}
并在模板中:
<app-container-header *ngIf="showContainerElements$ | async"></app-container-header>
<app-container-sidebar *ngIf="showContainerElements$ | async"></app-container-sidebar>
<app-container-footer *ngIf="showContainerElements$ | async"></app-container-footer>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.