Conceal the toolbar element if it is not at the top of the page

I am encountering an issue with my toolbar. When I scroll down, the transparent background of the toolbar disappears and it looks like this: https://i.sstatic.net/YxZQe.png. How can I hide this component when the page is scrolled down and show it again when scrolling back up to the top of the page? Apologies for any language barriers due to my limited English proficiency.

EDIT: I am using a mat-toolbar

<mat-toolbar color="primary">

<button mat-button routerLink="/" [ngStyle]="{'color': colorStyle === 'WHITE' ? 'white' : 'black'}">
<mat-icon>home</mat-icon> 
{{ 'PAGE.HOME' | translate}}</button>

<!-- This fills the remaining space of the current row -->
<span class="fill-remaining-space"></span>
<div fxLayout="row" fxShow="false" fxShow.gt-sm [ngStyle]="{'color': colorStyle === 'WHITE' ? 'white' : 'black'}">
    <button mat-button routerLink="['/home']">{{ 'PAGE.HOME' | translate}}</button>
    <button mat-button routerLink="['/home']">{{ 'PAGE.D9' | translate}}</button>
    <button mat-button routerLink="['/home']">{{ 'PAGE.DThuDuc' | translate}}</button>
    <button mat-button routerLink="['/home']">{{ 'PAGE.MORE' | translate}}</button>
    <button mat-button [routerLink]="['/add']">{{ 'PAGE.ADD' | translate}}</button>
    <button mat-button [routerLink]="['/login']" *ngIf="!loginStatus">{{ 'PAGE.LOGIN' | translate}}</button>
    <button mat-button [routerLink]="['/login']" *ngIf="loginStatus">{{ 'PAGE.LOGOUT' | translate}}</button>
    <button mat-button [routerLink]="['/show-map']" [queryParams]="{ lat: data.lat, lng: data.lng}">{{ 'PAGE.OVERVIEW' | translate}}</button>



</div>
<button mat-button [mat-menu-trigger-for]="menu" fxHide="false" fxHide.gt-sm>
 <mat-icon>menu</mat-icon>
</button>

</mat-toolbar>

.mat-toolbar {

    position: fixed;
    z-index: 999;
}

Answer №1

Utilize @HostListener window:scroll for better functionality

  @HostListener("window:scroll", [])
  onWindowScroll() {
    let number = window.pageYOffset || 0;
    console.log(number);
  }

Suggesting not to reference the window directly, Brian Love introduces a "window-provider": check out

The approach proposed by Brian Love:

****The following is an excerpt from the referenced article ********

import { isPlatformBrowser } from "@angular/common";
import { ClassProvider, FactoryProvider, InjectionToken, PLATFORM_ID } from '@angular/core';

/* Create a new injection token for injecting the window into a component. */
export const WINDOW = new InjectionToken('WindowToken');

/* Define abstract class for obtaining reference to the global window object. */
export abstract class WindowRef {

  get nativeWindow(): Window | Object {
    throw new Error('Not implemented.');
  }

}

/* Define class that implements the abstract class and returns the native window object. */
export class BrowserWindowRef extends WindowRef {

  constructor() {
    super();
  }

  get nativeWindow(): Window | Object {
    return window;
  }

}

/* Create a factory function that returns the native window object. */
export function windowFactory(browserWindowRef: BrowserWindowRef, platformId: Object): Window | Object {
  if (isPlatformBrowser(platformId)) {
    return browserWindowRef.nativeWindow;
  }
  return new Object();
}

/* Create an injectable provider for the WindowRef token that uses the BrowserWindowRef class. */
const browserWindowProvider: ClassProvider = {
  provide: WindowRef,
  useClass: BrowserWindowRef
};

/* Create an injectable provider that uses the windowFactory function for returning the native window object. */
const windowProvider: FactoryProvider = {
  provide: WINDOW,
  useFactory: windowFactory,
  deps: [ WindowRef, PLATFORM_ID ]
};

/* Create an array of providers. */
export const WINDOW_PROVIDERS = [
  browserWindowProvider,
  windowProvider
];

In the component's constructor

constructor(@Inject(WINDOW) private window: Window)

In the Module

@NgModule({
  declarations: [..]
  imports: [..]
  providers: [WINDOW_PROVIDERS,...],
})

Answer №2

To enhance the design, include the following CSS properties: Position:fixed; z-index:1000; Apply these styles to the primary div element within the header section.

Answer №3

To implement a function that is called when the window is scrolled, use

(window:scroll)="eventToBeCalled()"
in the body tag.

Make sure to assign an id to the toolbar like this:

<mat-toolbar color="primary" id="matTB">

In your typescript file, include the following code:

eventToBeCalled(): void {
   const matToolBar = document.getElementById('matTB');
   if(window.scrollY > 104)
   {
    matToolBar.setAttribute('style', 'display:none');
   } else {
    matToolBar.removeAttribute('style');
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulating the 'display' attribute with jQuery

Is there a way to show an element that has been hidden using the following CSS? .pds-pd-link { display: none !important; } Can jQuery be used to enable the display of the .pds-pd-link CSS? For example, would $(.pds-pd-link).css("display",""); ...

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

Carousel-Owl, glide through two items simultaneously

I am currently in the process of developing a slider using the beta version of Owl-Carousel 2, but I am encountering several issues. My goal is to configure the owlCarousel to function as follows: It should scroll through 2 items at a time while displayin ...

Using CSS, create a layout with a small 2x2 box positioned beside a larger 2x2 box

https://i.sstatic.net/nC2PI.png Can a flexible ul li structure be achieved with flexbox? I attempted to set the width of the squares to 25% and make the 1st, 3rd, or 5th one 50% wide using a combination of float:left, clear[left|right], but the last squar ...

trouble with padding on cards using vue-bootstrap

I have been working on creating a card component with Vue Bootstrap, but I've run into an issue. The card header and body seem to have excessive padding around them. If I remove the b-card element and only use b-card-header and b-card-body, it looks l ...

Adding margin to an HTML element causes the entire page to shift downward

Despite successfully applying margin to other elements, I encountered an issue with #searchbarcontainer where it causes the entire page to shift downward. My goal is to center it slightly below the middle of the page, but I'm struggling to find a solu ...

Eliminate the standard blue border that appears when control-clicking on table elements

I've encountered this question before, but unfortunately none of the solutions provided have worked for me. Some things I've attempted are: Using event.preventDefault() - did not produce the desired result. Removing user-select from CS ...

The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to ...

Is there a way to assess Python code within a document's context using JavaScript in JupyterLab?

When using Jupyter Notebooks, I can create a cell with the following JavaScript code: %%javascript IPython.notebook.kernel.execute('x = 42') After executing this code, in another cell containing Python code, the variable x will be bound to 42 a ...

steps for applying a vertical-align:bottom with an additional 10px offset

Can you show me how to have two inline-blocks with the second one positioned 10 pixels up from the bottom? I'm not sure how to do this. Here is a snippet of my code: .test1{ display:inline-block; border: 1px solid red; min-height: 50px; } .tes ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...

Calculate the quantity of rows within a specific div container

Looking at the image provided, there are multiple divs inside a main div. I am trying to figure out how many rows the main div contains. For instance, in this particular scenario, there are 5 rows. It is important to mention that the inner div is floated ...

"Failure to manipulate the style of an HTML element using Vue's

<vs-tr :key="i" v-for="(daydatasT, i) in daydatas"> <vs-td>{{ daydatasT.Machinecd }}</vs-td> <vs-td>{{ daydatasT.Checkdt }}</vs-td> <vs-td>{{ daydatasT.CheckItemnm }}< ...

We are currently moving up from NG 12 to NG 16 and encountering an issue with the package "@ng-bootstrap/ng-bootstrap" due to an incompatible peer dependency

When attempting to upgrade from Angular version 12 to version 13, we encountered some dependency errors. Following the instructions at https://update.angular.io/?v=12.0-13.0, we tried running ng update @angular/core@13 @angular/cli@13. We received the fo ...

Flex sidebar collapse menu

I am currently in the process of developing an admin panel for my website. I have a sidebar menu that I would like to hide behind a hamburger icon and only expand when clicked on. After researching potential solutions, I haven't found much that fits m ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

Issue: Generated JavaScript files not visible in Visual Studio when using TypeScript.Explanation: When working with

Is there a way to locate the JavaScript files generated from the TypeScript file in Visual Studio 2015? It seems that although the JavaScript files are present in File Explorer, they are not visible in the solution explorer. I attempted to add the _refer ...

Creating a dynamic array in an Angular 2 service for real-time changes monitoring by a component

I am facing an issue where my NotificationsBellComponent is not receiving changes to the array in the service even though the _LocalStorageService is returning data correctly. Q) How can I ensure that my component receives updates when the service collect ...

Organizing grid elements within the popper component

I am struggling to align the labels of options in the AutoComplete component with their respective column headers in the popper component: https://i.stack.imgur.com/0VMLe.png const CustomPopper = function (props: PopperProps) { co ...

The spacing between images on mobile devices is excessive

My images on mobile have too much space between them: mobile version They appear fine in Dev Tools: dev tools version This is my HTML: <div class="container-fluid"> <!-- <br> --> <div class="row"> ...