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?
You just need to generate a WindowRef.ts, put all the code inside of that and inject it into the component where you want to use the window object. In the latest version of Angular it's not even necessary any more.
Refactoring a component’s code, HTML, and CSS into three separate files [in the same package] is a common Angular Best-Practice. This practice of using external files is especially important when your HTML or CSS is non-trivial.
It turns out this ancestor had a CSS transform applied which resulted in it being the element in questions containing block which means that the fixed position elements positioning is relative to this element.
There is no npm package, as Window Ref is a component which has also been defined in the blog post. You just need to generate a WindowRef.ts, put all the code inside of that and inject it into the component where you want to use the window object. In the latest version of Angular it's not even necessary any more.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With