3

I'm trying to make a collapsible navbar with the help of MaterializeCSS when used on mobile screen and need to use JavaScript code in it. Where should I write this JavaScript code?

This is the code I want to use:

**$(document).ready(function(){
    $('.sidenav').sidenav();
  });**
1
  • 1
    you should write in the component file Commented Nov 26, 2018 at 13:38

3 Answers 3

10

Step-1: Created a js folder inside the assets folder.

Step-2: Created a new .js file inside the js folder. Assets -> js -> example.js

Step-3: Added path of the example.js in angular.json inside the scripts array.

Step-4: Declared the js function created in example.js inside the component.ts file where that function is needed.

Step-5: Made a call to the declared function inside ngOnInIt().

Sign up to request clarification or add additional context in comments.

Comments

4
  1. Install jQuery npm install jquery
  2. Install MaterializeCSS npm install materialize-css@next
  3. Install types npm install --save @types/materialize-css @types/jquery
  4. Open angular.json and find scripts field
  5. Add node_modules/jquery/dist/jquery.min.js and node_modules/materialize-css/dist/js/materialize.min.js inside array:
"scripts": [
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/materialize-css/dist/js/materialize.min.js"
]
  1. Go to your component and add at the top declare var jQuery: any;

Example

(function ($) {
    $('.sidenav').sidenav();
})(jQuery);

You can use that inside ngOnInit.

8 Comments

getting this error TypeError: $(...).sidenav is not a function
I already have materialize script inside the array and still getting the same error
Did you install types? And in angular.json there are 2 scripts fields.
Yeah, I did both.
Make sure that jQuery is first in array, then MaterializeCSS. And changes in angular.json require you to restart webservice. So just stop and start angular again. @harshitraghav
|
2

Find and open angular.json, then add to projects.architect.build.options object next field and change filepath to your own:

"scripts": [
  "path/to/js/you/want/use.js"
]

Angular will add those custom files to result build

1 Comment

I have created a file and added it's path like you said but how to use it inside the component?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.