The 'ng-scroll' component does not have a defined @viewchild

I am encountering an issue where the dayavailablescroll reference is showing as undefined in the ngAfterViewInit method.

<div class="shifts-rightTable " style="background-color: yellow" [ngClass]="{'tab-active':availData?.length}" >
                <ng-scrollbar #dayavailablescroll  [autoHeightDisabled]='false' track='horizontal'>

                <table class="table" >
                    <tbody>
                        <tr *ngFor="let secondValue of availData;let s = index;">
                            <td>
                                <div class="shift-scheduleWrapper dayLeaveIcons" *ngFor="let thirdValue of secondValue.user_roster_data;let m = index;">
                                    <div class="shift-scheduleList" [ngClass]="{'removeLeftspace':(thirdValue.day_status != 'Exchanged' && thirdValue.day_status != 'Scheduled' && thirdValue.day_status != 'Full day leave' && thirdValue.day_status != 'Exchange-Requested')}" [ngStyle]="{left:thirdValue.starTime + 'px',width: thirdValue.totalWidth + 'px'}" *ngIf="thirdValue.schedule_id  && thirdValue.day_status != 'Holiday' && thirdValue.day_status != 'Weekend' && thirdValue.leave_status != 1 && thirdValue.day_status != 'Full day onduty'" (click)="$event.stopPropagation();setShow(s,m);closeOthers(s,m);selectedId = thirdValue.schedule_id;save...

typescript

Upon inspecting, the value of this.dayavailablescroll in ngAfterViewInit shows undefined.

Answer №1

To access an element in the template from TypeScript code in Angular, you can use the ViewChild decorator after the template has finished rendering (using the AfterViewInit lifecycle hook).

@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
  @ViewChild('dayavailablescroll') scrollElem: ElementRef;

  ngAfterViewInit() {
     console.log( this.scrollElem);
  }
}

It's important to be mindful of situations where the element may not be accessible. If the element is not present in the template when you try to query it, it will not be found.

You can also consider using a type like ng-scrollbar instead of ElementRef if applicable.

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

"Unable to convert object into a primitive value" error message appears on Internet Explorer

Currently working on a webpage using Angular 7. The code is functioning perfectly in Chrome, however, I am facing an Exception error while running it in IE: An issue arises: Can't convert object to primitive value (polyfills.ts) The source of the er ...

I'm attempting to retrieve mlab data in the console using node.js, but unfortunately encountering an error

I came across this helpful YouTube tutorial:https://www.youtube.com/watch?v=PFP0oXNNveg&t=460s. I followed the steps outlined in the video and made necessary code adjustments based on current updates found through a Google search (to resolve errors enc ...

Is there a way to transfer query parameters to my resolver function?

Here is how I initialize the component in my ngOnInit method: ngOnInit() { this.route.queryParams.subscribe( (params) => { console.log(params); } ) } This is my resolver code: class ProductsResolver implements Resolve< ...

Issues encountered when working with Angular Material 2

Embarking on my project with Angular-material2 has proven to be quite challenging. Despite my efforts to import components correctly, I am encountering errors after importing material modules in my app.module.ts file. The error message reads: Uncaught Err ...

How do you properly perform typechecking on a custom fetch function in ReactQuery? I'm encountering an error that states: "....is of an unknown type."

Currently, I am working with typescript + react-query and creating a custom fetch function. I am struggling to properly type this function and encountering a TypeScript error when attempting to use myQuery.error.message const locationQuery: QueryObserverRe ...

Angular2: Issues with loading components

I have been experimenting with angular2 and attempting to work with attribute directives. However, I am encountering difficulties in loading components and I am not sure what mistake I might be making. Plunk: http://plnkr.co/edit/o3llvK?p=preview app.ts: ...

The npm installation process has come to a sudden halt

Starting a web application in Angular 17 has been my goal. I typically run npm install followed by ng serve. However, this process suddenly stopped working. To troubleshoot, here are the steps I've taken: Updated npm to the latest version (10.2. ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

The source 'http://localhost:4200' is being denied access by the CORS policy when using SignalR with .NET Core and Angular

In my Angular application, I am using SignalR to fetch real-time data and a .NET Core 2.2 API for the back-end. However, upon running the project, I encounter CORS errors in the browser console. VehicleHub.cs using Microsoft.AspNetCore.SignalR; using Sys ...

No input in ng2-select2

How can I reset the value in ng2-select2 by clicking on a button? Here is my current HTML code: <select2 id="bill" [data]="colBill" [options]="option" (valueChanged)="onBillArray($event);"> The corresponding Typescript code is: this.arrBill = []; ...

Resolve the result of the HttpComponent within the Service component

Consider this example involving HttpClient: In Service configData: string[]; fetchData(): Observable<string[]> { return this.http.get<string[]>('./assets/config.json'); } getConfigValue(key: string): string { if ...

Can you explain the significance of { 0: T } in this particular type definition?

I stumbled upon this type declaration in my codebase which is meant for non-empty arrays: type NonEmptyArray<T> = T[] & { 0: T } and it functions as expected: const okay: NonEmptyArray<number> = [1, 2]; const alsoOkay: NonEmptyArray<n ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Connecting ASP.NET Core null values with Angular2 null: A Step-by-Step Guide

Currently, I am working on a web application that is built using .NET Core and Angular 2. The issue I am facing is related to the currency parameter that I am sending from my database to Angular 2. Right now, the currency value is NULL, so Angular 2 receiv ...

Is it possible to achieve pagination by simply dragging the scroll bar to the top or bottom position?

Recently, I've been working on implementing a pagination function for a list of items. The pagination currently works well with scrolling events - it automatically moves to the next page when scrolling to the bottom, and to the previous page when scro ...

Prevent toggle button from activating panel expansion

Is there a way to add toggle buttons to the description section of an expansion panel without triggering the expansion panel when interacting with the buttons? I have included an example here. ...

I am working on an Angular application that includes a dynamic form for an attendance system for employees. I am currently trying to figure out how to generate the JSON data

I have a dynamic form in my reactive attendance system for employees. When I click on submit, I need to generate JSON data like the following: { "user_id": "1", "branch_id": "4", "auth_token": "59a2a9337afb07255257199b03ed6076", "date": "2019- ...

Can we create a generic constraint that utilizes an index, be it a type or an object?

I am currently generating client models (Entities) along with their corresponding Primary Keys. My goal is to create a method signature where, based on the Entity provided, the second parameter should be its Primary Key only. The specific use of types an ...

Utilize personalized Bootstrap variables within your Angular application

I am attempting to customize the default colors of Bootstrap within my Angular project. I have established a _variables.scss file in the src directory. Within this file, I have included the following code: $primary: purple; Next, I imported my _variables ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...