jloosli
jloosli

Reputation: 2581

Fixed element is relative to component, not window in Angular2

I have an angular2 application using the Angular2-material library for styling. I'm trying to add a FAB (Floating Action Button) to hover in the right corner of the application, but it's fixing itself to its parent component, and not the window.

The hierarchy of the application is as follows:

app.component
|-detail.component

Within the app.component template, I am using the md-sidenav-layout directive with router-outlet in the body of the layout directive:

<md-sidenav-layout>
  <md-sidenav #sideNav (open)="closeStartButton.focus()">
    <router-outlet name="navMenu"></router-outlet>
    <br>
    <button md-button #closeStartButton (click)="sideNav.close()">Close</button>
  </md-sidenav>
  <md-toolbar color="primary">
    <button md-icon-button (click)="sideNav.toggle()">
      <md-icon class="md-24">menu</md-icon>
    </button>
    <span>{{title}}</span>
  </md-toolbar>
  <div role="main">
    <router-outlet></router-outlet>
  </div>
</md-sidenav-layout>

Inside the detail component template, I have the following at the top of the template:

<button md-mini-fab class="fab" (click)="toggleAdd()">
  <i class="material-icons">add</i>
</button>

And the css for that component:

.fab {
  display: block;
  position: fixed;
  right: 2rem;
  bottom: 2rem;
  z-index: 10;
}

However, when I navigate to the detail page, the .fab is positioned relative to the component, not the window. I've tried using encapsulation: ViewEncapsulation.None on the detail component, but that doesn't affect it either. Is there a way to keep the fab defined within the detail component, but have it still be fixed relative to the window?

Upvotes: 7

Views: 5202

Answers (3)

Sergey Andreev
Sergey Andreev

Reputation: 1488

in your app.component.html add this code:

<md-sidenav-container>
    <md-sidenav mode="side" opened="true">Drawer content</md-sidenav>
    <div class="my-content">Main content</div>
</md-sidenav-container>

global styles.css:

html, body, material-app, md-sidenav-container, .my-content {
    margin: 0;
    width: 100%;
    height: 100%;
}

it works for me! ;)

Upvotes: 6

I answered a very similar question here.

The gist: I solved this with a quite heavy workaround. I removed the FAB from the main content, defined a secondary router outlet in my template (outside md-sidenav-layout), created a standalone component for the FAB, and used an Observable in a service to broadcast the click events to the main components.

The answer in the other thread contains code samples and a working plunker example.

Upvotes: 2

Andrew
Andrew

Reputation: 169

Look for something applying a CSS transform up the chain. In my case I was applying a transform via Angular animations. Apparently transform breaks position:fixed. Why does `transform` break `position: fixed`?

I hope I can figure out how to make this work, now.

Upvotes: 6

Related Questions