JavaScript/jQuery: neglecting to incorporate a function within Angular

I'm attempting to implement a French datepicker in Angular, but I'm encountering difficulty in invoking the function within my component.

datefrench.js

!function(datefrench){datefrench.fn.datepicker.dates.fr={

days:["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],
daysShort:["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],
daysMin:["d","l","ma","me","j","v","s"],
months:["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"],
monthsShort:["janv.","févr.","mars","avril","mai","juin","juil.","août","sept.","oct.","nov.","déc."],
today:"Aujourd'hui",
monthsTitle:"Mois",
clear:"Effacer",
weekStart:1,
format:"dd/mm/yyyy"}}(jQuery);

add-date.component.ts

  import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormBuilder, FormControl, Validators, Form } from '@angular/forms';
    import { Router } from '@angular/router';
    
    declare var datefrench;
    declare var $:any;
    
    @Component({
      selector: 'app-add-date',
      templateUrl: './add-date.component.html',
      styleUrls: ['./add-date.component.css']
    })
    export class AddDateComponent implements OnInit {
    
    
      constructor(private router: Router) { }
    
      ngOnInit() {
        $(function () {
        $('#mydate').datepicker({
         language: 'fr'})
        });
        }
    }

add-date.component.html

<input type="text" id="mydate" name="mydate">

Unfortunately, an error message keeps appearing stating that the function datepicker is not being recognized.

PS: all assets (javascript/css..) are properly included

Answer №1

If you have not included the script path in the angular.json's corresponding scripts section, you may encounter issues.

When adding third-party JavaScript that does not support ES6 modules, follow these steps:

  1. Install the script and its dependencies using npm install ->
    npm install jquery npm install myJqueryPlugin
  2. If you are using TypeScript, make sure to install types for the jQuery plugin. If types are not available, you can manually create them as shown in How to add third party plugin jquery on angular 7?
  3. Check for
    "types": [ "jquery", "whatever" ]
    in the tsconfig.app.json
  4. In the angular.json or angular-cli.json, ensure that it is added in the scripts section. This step is crucial, so try this first.
"scripts": [
  "../node_modules/jquery/dist/jquery.slim.js",
  "others ie. jquery plugin in your case with correct path"
]
  1. The script should be accessible through the window object, like window['datefrench'].
  2. Alternatively, instead of step #5, you can use declare var $; as you did.

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

After installing an npm package from GitHub, I encountered an issue where the package could not be resolved, causing issues with my Angular

After encountering a few issues with a package, I had to fork it and make some fixes. Although the npm install process seems to go smoothly and the package appears in node_modules https://i.sstatic.net/vpvP1.png I am facing build errors (unable to resolv ...

Adding information to a designated included component (Angular)

I am trying to develop a directive for generating multiple choice activities. The concept is that within my scope, I hold a model containing an array of questions structured like this: function Controller($scope) { $scope.activity1 = { "questions" ...

extract objects from an array based on a specific property that meets a given condition

Currently, I am facing the challenge of filtering an array of objects based on a specific property that matches what the user has entered. Here is the array I am working with: peopleList = [ {name: "john bee", age:23}, {name: "john woo", age:43}, ...

What is the best way to overlay text onto a background image using Material UI's Card and CardMedia components?

Using the card component, I have successfully added a background image. However, I am facing difficulty in figuring out how to overlay text on top of this image. If anyone has suggestions or alternative methods, please feel free to share! <Card> ...

Issue with PrimeNG overlaypanel displaying error message "Functionality of this.engine.setProperty is not available"

After importing OverlayPanelModule as @NgModule in parent.module.ts, I added the following code in child.component.html: <p-overlayPanel [dismissable]="false" #overlay> Content </p-overlayPanel> However, upon testing, I encountered the error ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

Make sure to wait for the scrollTo function to finish before executing any other commands

I have a sleek scrolling directive in my AngularJS app that automatically scrolls to the bottom of the page. I want this command to execute only after the scrolling has completed. Currently, I trigger the scroll function and then use $('#comment-input ...

Deciphering the outcomes of Promise versus Observables

Query: Methodology fetchDataQuery(): any { let query = new Query((resolve, reject) => { resolve([ { name: 'Apple', type: 'fruit' }, { name: 'Banana', type: 'fruit' } ]); }); ...

Can you combine multiple items in PaperJS to move them collectively?

I'm working on a PaperJS project that involves numerous circles that can move independently. In addition to this, I would like each circle to have PointText at its center acting as a label. However, instead of having to manually animate each label ev ...

What could be the reason for only one of my states being modified when I call my function?

Currently, I have a single state in React.js consisting of two key-value pairs for length validation and character validation: const [validation, setValidationState] = useState({ lengthValidation: "", characterValidation: "", }); These states are e ...

When utilizing Express, only the index.html page is rendered, all additional pages

I've set up an express app specifically for serving static HTML files. let express = require('express'); let path = require('path'); let cookieParser = require('cookie-parser'); let logger = require('morgan'); ...

Error occurred while trying to implement style due to unsupported MIME type ('text/html') for the stylesheet

I am encountering multiple errors while attempting to access my application: Encountered errors while trying to load the application:</p> <pre><code>Refused to apply style from 'http://localhost:8000/styles.2466d75470f9c2227ee1.css&a ...

How can I use Grid List and Icon Button in Material UI as individual buttons with onClick functionality?

I've been experimenting with the grid list feature from the Material UI framework, found here: https://material-ui.com/components/grid-list/#grid-list-with-titlebars My current challenge involves adding onClick actions to both the GridListTile compon ...

Updating a textbox with JQuery AJAX when the text in another textbox changes

Whenever I type something into an input field with the id "textbox1", I want to update another input field with the id "textbox2" accordingly. This is the code I started with: $("#textbox1").keyup(function(){ $.ajax({ type: "POST", ...

Using JSON Filtering with React

I am currently working on fetching JSON data and implementing a filtering feature for the displayed content. An error that I am encountering is: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined Any insights on what might be ...

Creating a tree structure from JSON data involves adjusting the entries as demonstrated below, utilizing programming languages for implementation

Data Entry: const info = [ { type: 'Electronics', category: 'cellphone', price: 800, profit: 50, }, { type: 'Clothing', category: 'shoes', price: 100, profit: 30, }, { ty ...

The json format was not used to transfer the response data

In the script below, I am trying to retrieve and display the requests that have been booked. The goal is to take the data received through JSON and append it to HTML. function readUsers() { //show ajax loader animation $( '#ajaxLoadAni' ...

To access ES Module, importing is necessary

I'm currently working on a project to develop a service that can convert SVG files into PNG format using the svg2img package. Everything is running smoothly when testing locally with vercel dev, but I keep encountering an error whenever I try to deplo ...

Clickable link remains functional after being hidden

Even though I have hidden the Games-div using the .hide() function in jQuery, my links are still clickable. Is there a way to make them unclickable after being hidden? Here is the link to my code on jsFiddle: http://jsfiddle.net/hypertje/Frv8G/ Note: The ...

Issue with Node/Express: Middleware addition to router does not function as expected

Here is the configuration of my router: app.get('/getReport', (req, res) => { res.send("This is the report"); }); Initially, this router functions properly and successfully displays the message This is the report in the browser However, ...