Explanation on How to utilize the $( document ).ready() jQuery function within the ngAfterViewInit() on a Component class using Angular 2

This is the code snippet:

constructor(private el: ElementRef) { }

ngAfterViewInit() {

    this.loadScript('app/homepage/template-scripts.js');       


}

Answer №1

Angular provides a way to avoid relying on jQuery by using lifecycle events:

(organized by lifecycle)

-ngOnChanges -ngOnInit -ngDoCheck -ngAfterContentInit -ngAfterContentChecked -ngAfterViewInit -ngAfterViewChecked -ngOnDestroy

If you need to use the jQuery function .ready, you can import jQuery as a dependency in your Angular project, then import the relevant module in your .ts file and call it within ngAfterViewInit:

// Before all else
// Start by installing jQuery
npm install --save jquery
// Next, add jQuery Definition
npm install -D @types/jquery

-----

import $ from 'jquery';
//

ngAfterViewInit() {
// other actions

if ($.ready()) {
    console.log('ready');
  }
}

The code above does work.

However, it is worth noting that this approach is not recommended as it mixes logic within existing Angular lifecycle methods.

https://angular.io/guide/lifecycle-hooks

I hope this explanation has been helpful.

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

Whenever the [required] tag switches from being true to false, it generates an event

Initially, I have set up an Angular form using the following code snippet buildForm() { this.form = this.formBuilder.group({ value1: this.formBuilder.control(null), value2: this.formBuilder.control(false) }); } The HTML contains a ...

The functionality of Angular is not compatible with a mobile network connection

Recently, I noticed that my Angular 6 application hosted on my server with SSL and HTTPS protocol loads quickly on my computer but is extremely slow on my mobile phone, taking about 3-4 minutes to fully load. I conducted network profiling using Chrome, bu ...

Locating and casting array elements correctly with union types and generics: a guide

My type declarations are as follows: types.ts: type ItemKind = 'A' | 'B'; type ValidItem<TItemKind extends ItemKind = ItemKind> = { readonly type: TItemKind; readonly id: number; }; type EmptyItem<TItemKind extends ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

Validating multiple conditions in Typescript by passing them as function parameters

As a beginner in TS/JS, I am looking to validate multiple conditions passed as arguments to a function. For instance, currently I am verifying the user role name, but in the future, I may need to check other conditions. validateUserDetails(): Promise< ...

Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend. { "components": [ { "label": "Textfield1", "type": "textfield", "key": "textfield1", ...

Is there a way to verify the presence of a room before transmitting a message to a socket?

sendToSpecificRoom(message: any): void { if(message.roomName){ this.io.sockets.in(message.roomName).emit("eventSent", message); }else{ this.io.sockets.emit("eventSent", message); } } I need to send a message specifically to the ...

Executing HTTP requests within a loop using AngularJS 2

I have been exploring the functionality of the YouTube API, and I am facing an issue with getting the icons for the first 'n' videos. For this, I need to make a request for each video. My initial thought was to use a for loop to handle these requ ...

Is it not possible to reinitialize angular/material's md-slide-toggle component?

In my Angular 2 application, I have a model-driven form that consists of two components: An Angular Material slide-toggle. A button that triggers the onReset(form: FormGroup) function in my Component when clicked. You can view an example on this Plunkr. ...

The address :::3000 is already in use by NestJS

While attempting to deploy my NestJs server on a C-Panel hosting, I have encountered an issue. Despite properly installing all node_modules and ensuring every project file is in place, the server fails to start and continuously displays the following error ...

When attempting to add images to a column using JsPDF Autotable, I encountered an error stating that the property 'getElementsByTagName' is not recognized

I'm attempting to include an image from an AWS S3 bucket using its URL. The data is structured in the following format: [{ netValue: 13702.5, prodCode: "UPP", prodDesc: "Privacy Panel", prodImg: "https://url/images/UPP ...

Just a straightforward Minimum Working Example, encountering a TypeScript error TS2322 that states the object is not compatible with the type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

Currently, I am immersed in a project involving React and Typescript. I am grappling with error code TS2322 and attempting to resolve it. Error: Type '{ submissionsArray: SubmissionProps[]; }' is not assignable to type 'IntrinsicAttributes ...

Angular 10 issue: Cart quantity in header shared component does not update when changed from another component

Whenever I click on the 'Add to cart' button, I want the number of items in the cart icon on the header component to increase. Currently, this only works when I refresh the page. In order to achieve this, I am using a cart service to store globa ...

I have a component that I utilized for subscription purposes. After subscribing to the method, I ensured to properly unsubscribe in order to prevent any memory leaks

Access code for services private postsData: Post[] = []; private updatedPosts = new Subject<Post[]>(); getPosts() { return [...this.postsData]; } getUpdatedPostsListener() { return this.updatedPosts.asObservable(); } addNe ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

React Typescript Context state isn't refreshing properly

Struggling to modify my context state, I feel like I'm overlooking something as I've worked with context in the past. The challenge lies in changing the 'isOpen' property within the context. You can view my code here: CodeSand **app.ts ...

The Typescript const assertion translated into Javascript

Is there a way in JavaScript to achieve constant-like behavior similar to TypeScript's const assertion? const arr = [1,2,3,4] as const I am looking for a solution in JavaScript that allows me to create an array that cannot be further mutated. ...

What does Typescript compile when aiming for ES5 / ES3?

I'm currently grappling with the nuances of when the Typescript compiler decides to transpile code in order to align it with my designated target ECMAScript version (ES5 or ES3). As an example, TSC has no problem transpiling for(var int of intArray); ...

What is the best way to open and view files in an NPM dependency that do not use JavaScript?

I am facing an issue with an NPM project setup where my-config is a dependency of my-api. In the my-config project, there is a line of code that fetches the aws-config.ini file from the etc folder: instance.configs.aws = ini.parse(fs.readFileSync('./ ...

Issue verifying the initial certificate in Nodeshift

Currently, I am in the process of deploying an Angular application using nodeshift, but I have encountered the error message "unable to verify the first certificate" whenever I execute the following command: nodeshift --strictSSL=false --dockerImage=buch ...