1

I am new to Angular and Materialize. I am trying to initialize a carousel within my Angular component.

Materialize mentions three ways:

M.AutoInit();

or

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.carousel');
    var instances = M.Carousel.init(elems, options);
  });

or

  $(document).ready(function(){
    $('.carousel').carousel();
  });

I have installed Materialize via node. I have both its CSS and JS as dependencies in my angular.json folder. The CSS styling works. I have tried these three methods within my ngOnInit lifecycle hook within my component. "M" is not recognized. I tried importing materialize:

import { materialize } from '../../../node_modules/materialize-css'

and

let m = materialize;

But this hasn't worked either.

I then installed jquery as a depedency and tried that method, but that doesn't seem to work either.

1
  • Share your code on stackblitz.com ? just give this a try import 'materialize-css'; Commented Oct 11, 2018 at 21:38

3 Answers 3

2
  • import OnInit from @angular/core library

  • declare const M: any; underneath imports

  • fire the M.AutoInit() function in ngOnInit() lifecycle hook

Example (where the component name is MediaComponent):

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

declare const M: any;

@Component({
  selector: 'app-media',
  templateUrl: './media.component.html',
  styleUrls: ['./media.component.scss']
})
export class MediaComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    M.AutoInit();
  }

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

Comments

1

You should use the Materialize for Angular library. Asking how to use jQuery with Angular can get you a lot of downvotes.

https://www.npmjs.com/package/angular2-materialize

1 Comment

I did not want to use jquery. I mentioned it only because after the first method of initializing didn't seem to work. I used the Materialize library for angular.
0

import { Component, OnInit } from '@angular/core'; declare var M: any;

1 Comment

This is a so-called code-only answer and without an explanation of why it helps not appreciated. Also learning about formatting would be beneficial Take the tour as something of a good-luck-charm and read How to Answer.

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.