Step-by-step guide on utilizing the vendor.ts file available at https://angular.io/docs/ts/latest/guide/webpack.html

As per the guidelines provided at https://angular.io/docs/ts/latest/guide/webpack.html, it is recommended to include vendors like jQuery in the vendor.ts file.

// Other vendors for instance jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...

This is my current approach:

typings install dt~jquery --global --save
npm install jquery --save

In addition, I inserted the following line into vendor.ts:

import 'jquery'

Although webpack runs without any errors, I am facing issues while trying to utilize jQuery in my Component.

import { Component, OnInit, ElementRef } from '@angular/core';

@Component({
  selector: 'table-widget',
  templateUrl: 'table-widget.component.html'
})

export class TableWidgetComponent implements OnInit {

 constructor(private _elRef: ElementRef) {

 }

 ngOnInit(): void {
   $(this._elRef.nativeElement).find('button').on('click', function() { alert("it works"); });
 }
}

What could possibly be the mistake in my implementation?

Answer №1

To make jQuery available globally, you can follow any of these methods.

If you are using webpack, you can add the following code to your webpack config:

plugins: [
    ....  //your other configs
    new webpack.ProvidePlugin({
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery'
    })
]

Alternatively, you can also use expose-loader:

module: {
  loaders: [
      { test: require.resolve("jquery"), loader: "expose?$!expose?jQuery" },
  ]
}

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

Troubleshooting Protractor in Intellij: A step-by-step guide

While using OSX, I successfully configured an Intellij 15 run/debug task as explained in this post below: How to debug angular protractor tests in WebStorm Although the task runs fine, unfortunately, the debug feature does not work and throws the followi ...

Processing a JSON array of objects in AngularJS

When using Angular's fromJson function to parse a JSON string, I encountered an issue. If the JSON is a simple array like "[1, 2]", the code works fine. However, I need to work with an array of dictionaries instead. var str = "[{'title' ...

Using Angular JS, the JSON method is invoked from a location external to the controller

How can I call an inner method from outside a controller in AngularJS? var app; (function (){ app = angular.module("gallery", []); app.controller("galleryController", ['$scope','$http', function($scope, $http){ var gallery = this; ...

The user interface does not get refreshed right away; it only shows the changes after the

Here is an example of HTML: <div ng-repeat="user in controller.users"> <p>{{user.name}}</p> <button ng-click="controller.deleteUser(user)" value="delete"></button> </div> Next, we have the controller code: vm ...

Creating PDFs in iOS and Android using Ionic framework

Seeking assistance with resolving this issue. I have researched extensively on Google, jspdf, pdfmake.org, inappbrowser plugins, but have been unsuccessful in getting my Ionic project to function properly. The goal is to create a simple form that includes ...

Exclude weekends from DateTime

Currently working on a task list and aiming to set the default date to 3 days from now, excluding weekends. Utilizing Vue and thinking a computed property might be the solution? DateTime.utc().plus({ days: 3 }).toFormat('yyyy-MM-dd HH:mm:ss'), ...

How to implement a distinct click event for input elements containing a pipe character in Angular

I have developed an innovative Elevator application that features a unique elevator component displaying the current floor value in a box. You can see how it looks here: https://i.stack.imgur.com/h3JW5.png In order to replace the numerical floor values w ...

What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used? enum FormType { ...

Using Angular Material's [mat-form-field], you can easily input a value into a text box

How can I programmatically add a value to a text box within a [mat-form-field] using a function? addValueToTextBox(){ ... } ...

Steps to invoke the Express JS code repository from a serverless repository

Within my current project, there exists various repositories housing Angular code, Express JS (node JS) code, and AWS serverless components. For a specific feature, I am tasked with transferring the 'userId' value from the Angular code to the ser ...

There was an error due to a TypeError: The 'page' property cannot be read because it is undefined

Can anyone assist me with an Angular issue I'm facing? I've been working on integrating server-side pagination, but no matter how many times I revise my code, I keep encountering the same error message: ERROR TypeError: Cannot read properties o ...

Obtain an Angular2/4 Carousel component through a service in order to create a seamless loop

I am currently working on implementing a carousel in Angular. While it is not complicated to include slide images directly in the html, I am interested in fetching them from an array stored in a service for more dynamic functionality. Here is a snippet of ...

AngularJS restricts inputs to be read-only

I'm facing an issue with readonly inputs in AngularJS. I have a select element that changes the values of readonly inputs through a script. However, when I attempt to display these values using ng-model in a table as {{ng-model}}, they don't appe ...

Issue TS2322 states that the type 'Observable<{} | T>' cannot be assigned to type 'Observable<T>'

Recently, I came across a useful example of error handling with the async pipe in Angular on this website: However, when attempting to implement it in Angular 7, I encountered compilation errors. readonly data$: Observable<T>; constructor(data: ...

Creating a predictive text feature using AngularJS and jQuery

Currently, I'm developing a web application that utilizes: JQuery AngularJS Kendo framework Specifically, I am tasked with implementing an auto-complete feature using Kendo on an input text field. Initially, my approach was to target the inp ...

MUI provides the flexibility to adjust the opacity separately for Chip labels/icons and backgrounds

My objective is to customize the opacity of label/icon and background in MUI Chip. I want the label & icon to have an opacity of 1, while the background should have an opacity of 0.0571. Technologies used in this project include React, TypeScript, Materia ...

Does SharePoint Online support the .webmanifest format? What is the process for creating a Progressive Web Application in SharePoint Online using a supported webmanifest file?

Currently, I am in the process of developing a Progressive Web Application for SharePoint Online by utilizing the Angular 8 PWA build. The service worker and application are running smoothly; however, I have encountered an issue with loading the webmanifes ...

Tips for transferring PHP response data between pages in AngularJS without relying on local storage

One question I have is how to transfer data from one page to another in AngularJS without relying on local storage, and ensuring that the data persists even if the user reloads the page. Are there any alternatives or solutions available for this situation ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

Having trouble installing the Angular/CLI on macOS Mojave due to a node-pre-gyp error?

I recently formatted my iMac and deleted all files on the hard drive. However, upon installing Angular CLI 7, I encountered an error log message in the terminal console. Environment macOS: Mojave 10.14.2 node: v10.15 npm: 6.4.1 Console Error miguels- ...