Lock the table header in place as the table content scrolls upward using Angular4

Is there a way to keep the table header fixed in place while the rest of the content scrolls up? Below is a snippet from my .html file:

 <table class="table sticky-header">
                  <thead>
                      <tr class="row-hor-heading">
                          <th colspan="3" scope="row"><span class="bank-name">{{offer.name}}</span> <br /><span class="offers-heading">{{offer.companyname}}</span></th>
                      </tr>
                  </thead>
                  <tbody>
                      <tr class="row-2-data bg-white">
                          <td colspan="3" scope="row">
                            <button class="btn offerapply-btn waves-effect waves-light" (click)="openThisOffer(offer,leadType)">I&#39;m Interested</button>
                          </td>
                      </tr>
                 </tbody>
   </table>

In my typescript file, I have written code within the afterViewInit() function as shown below:

 ngAfterViewInit(){

  // Add code here

}    

I'm unsure of what needs to be included inside the function. Any assistance on how to achieve this would be greatly appreciated. Thank you!

Answer №1

Have you attempted implementing this code snippet in your component.ts file?

public fixed: boolean = false; 
constructor(@Inject(DOCUMENT) private doc: Document) {}
     @HostListener("window:scroll", [])
     onWindowScroll() {
        let num = this.document.body.scrollTop;
        if ( num > 50 ) {
        this.fixed = true;
        }else if (this.fixed && num < 5) {
        this.fixed = false;

Then, simply update the table element to:

<table [class.fixed]="fixed" class="table sticky-header">

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

I am faced with a challenge involving an asynchronous function and the best approach to executing it synchronously

I devised the following plan: // Primary Function to Follow // Capture necessary local data // Transform into required editable format // Iterate through user's local images // Append image names to converted d ...

"Tips for removing all child elements from a parent element using Angular's Renderer2 in versions 5 and above

Manipulating the DOM programmatically is recommended using Angular's Renderer2. Within my directive, I extract some text from el.nativeElement.innerText, modify it, and aim to append it to my element: const text = renderer.createText(`${el.innerTex ...

Using Typescript: A guide on including imported images in the output directory

typings/index.d.ts declare module "*.svg"; declare module "*.png"; declare module "*.jpg"; tsconfig.json { "compilerOptions": { "module": "commonjs", "target": "es5", "declaration": true, "outDir": "./dist" }, ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...

:host-selector for Angular Material dialog

I am currently working with a dialog component provided by angular-material and I need to customize the appearance of the popup dialog. I am aware that there is some support for styling through the component generation: let dialogRef = dialog.open(MyDi ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

Is there a way to enlarge the font size for a complete tag?

I'm having trouble with a project. One of the tasks is to use jQuery or JavaScript to increase the font size of a paragraph. The console statements are incrementing by +1 with every mouse click (the first click adds 1, the second adds 2, and so on). ...

Trigger change event on model update in Angular 4 checkboxes

CSS <div class="checkbox-item"> <input type="checkbox" id="1" [(ngModel)]="filter" (change)="onFilterChange($event)"> CheckBox </div> <button (click)="filter = !filter">Change Status</button> JavaScript export class Filt ...

How to display content in separate divs using jQuery hover functionality

I'm in the process of creating my online portfolio by using bootstrap and jquery. I have a series of images arranged side by side with each other, and I want to make the description for each image appear when that specific image is hovered over. Each ...

Creating Instances of Parameterized Types

Consider the following scenario: class Datum {} An error message (error TS2304: Cannot find name 'T') is encountered when attempting the following: class Data<T extends Datum> { datum: T constructor() { this.datum = new ...

Performing an HTTP POST request in Angular 2

After starting my work with Angular 2 and TypeScript, everything was going great. However, I encountered an issue when working with a REST API (POST) where the console log displayed Response {_body: "", status: 204, statusText: "Ok", headers: Headers, type ...

Unleashing the power of storytelling with React: A guide to creating dynamic story

weather.stories.ts export default { title: 'Widgets/Forecast', component: Weather, } const Template: Story<any> = (args) => <Weather {...args} />; export const Default = Template.bind({}); Default.args = { forecast: { ...

Encountering "Invalid hook call" error with React Router while integrating Higher Order Components for authentication

Dealing with an error: React Router shows "Invalid hook call" with higher-order components for authentication Dilemma I have developed two distinct approaches for authentication wrappers in my React components with React Router. The first method functions ...

Searching for a way to retrieve all information based on the parent in a dynamically dependent Laravel system?

Is there a way to fetch all child data by default in a dropdown list, but still have the option to select parent data when needed? I am using AJAX and I'm new to it. Edit: I have a 'category' dropdown with dynamically loaded parent data fro ...

Issue with initial navigation in MVC app causing Angular app routing to fail

Encountering a problem with navigating within an Angular app hosted on an MVC page. While most of the functionality is working smoothly, there is one scenario where the URL changes but the new page is not displayed. Let's simplify the setup (this iss ...

Error encountered in Typescript: The property 'prevUrl' is expected to be present in the props object, but it appears to be missing

When trying to access the props.prevUrl property, the following error is encountered: Property 'prevUrl' does not exist on type '{ nextUrl: string; } | { prevUrl: string; nextUrl: string; } | { prevUrl: string; confirm: () => void; }&apos ...

Angular2 Edit form does not have radio button selected according to the value

When editing a form, the radio button does not appear checked according to the value retrieved. I was able to retrieve the last name from the database, but when trying to bind the gender with the radio button, it does not show as checked. <div clas ...

Encountering issues with Next.js routing - Pages failing to load as expected

Having some trouble with the routing in my Next.js application. I've created a page named about.tsx within the "pages" directory, but when trying to access it via its URL (localhost:3000/about), the page fails to load correctly and displays: This Pa ...

Working with post metadata in functions.php and making AJAX requests

I may be inexperienced, but I am struggling with this issue. Why is it that when I perform the following: function my_f() { $sss = 'some data'; echo ($sss); die(); } add_action('wp_ajax_nopriv_my_f', 'my_f'); add_acti ...

Providing a conditional getServerSideProps function

Is there a way to dynamically activate or deactivate the getServerSideProps function using an environment variable? I attempted the following approach: if (process.env.NEXT_PUBLIC_ONOFF === 'true') { export const getServerSideProps: Get ...