Search code examples
angularmaterialize

formSelect() method in materialize does'nt work in angular 6 inputs


I'm using materialize CSS combined with angular 6, my problem is that the input's label if they load data from some services, the label overlaps with the text of the input.

In their official documentation, they use this code to fix this behaviour:

$(document).ready(function(){
    $('select').formSelect();
  });

but if i use this code in the ngOnInit() or even the ngAfterViewInit(), it fails with this error:

error TS2339: Property 'formSelect' does not exist on type 'JQuery'.

I have Jquery imported, obviously is not detecting the materialize script. I tried importing the script from CDN and in the angular.json like this:

 "styles": [
              "src/styles.css",
              "node_modules/materialize-css/dist/css/materialize.css"       
            ],
            "scripts": [  
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/materialize-css/dist/js/materialize.js"]

What do I need to do to fix this? looks that's the angular app is not loading the script or if it's loading the script, it's too early to call the function.


Solution

  • That's because you have imported jquery like this:

    import * as $ from 'jquery';
    

    try this instead:

    $: any // declare dollar sign as a field variable
    

    The reason it should work is when you are importing $ from jquery it looks for formSelect() method in jquery method but it's a materialize.js method. when you declare $ as an any your code compiles successfully and now because you've added jquery and materialize.js to your scripts in your angular.json in the application run it recognizes .formSelect() on $