首页 > 解决方案 > Angular 工具栏固定在顶部

问题描述

我有一个由我和其他组件创建的工具栏。在 app.component 我有这样的东西:

<app-toolbar>
</app-toolbar>

<main>
    <a [routerLink]="['/login/en']"></a>
    <router-outlet></router-outlet>
</main>

我想使用“position=sticky”以便在滚动期间工具栏始终位于顶部,但我不能使用它,因为我没有每个组件的工具栏。我正在使用 Angular 5。有简单的方法吗?谢谢。

标签: angulartypescript

解决方案


您可以创建一个“模板组件”,其中包含工具栏 + a <ng-content>

在示例中,我们假设您创建了一个带有选择器的模板,例如<app-toolbar-template>

工具栏模板.ts

@Component({
  selector: 'app-toolbar-template',
  templateUrl: './toolbar-template.html',
  styleUrls: ['./toolbar-template.css']
})
export class ToolbarTemplateComponent {}

工具栏-template.html

<div id="toolbar">Fake toolbar</div>

<ng-content></ng-content>

然后,当您创建组件时:

  • 如果您需要工具栏,请将内容放在<app-toolbar-template>标签内
  • 如果您不需要工具栏,只需放置您的内容。
  • 工具栏管理的 CSS 将写在toolbar-template.css

foo.component.html

<!-- With the toolbar -->
<app-toolbar-template>
  <div>Content</div>
</app-toolbar-template>

OR just 

<!-- Without the toolbar -->
<div>Content</div>

工作演示在这里


推荐阅读