简体   繁体   中英

Angular 6, Materialize: initializing javascript

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.

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

  • 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();
  }

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM