Search code examples
angularmaterialize

Materialize in Angular 10 - CSS being applied, but JS not executing


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

I've installed Materialize-css and have css and js in angular.json.

The CSS works perfectly, but the js doesn't work, including modals, carousel, etc. A sidenav worked adding M.AutoInit() in index.js.

This is the component.html:

<div class="row">
  <div class="col l4 m6 s12" *ngFor="let field of fields">
    <div class="carousel">
      <a class="carousel-item" href="#one!"><img [src]="'http://localhost:3000/'+field.imagePath"></a>
    </div>
  </div>
</div>

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

This is the component.ts

import { Component, OnInit  } from '@angular/core';
import { FieldService } from '../../services/field.service'

declare const M: any;

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})

export class MainComponent implements OnInit {

  fields= [];

  constructor(
    private fieldService: FieldService,
  ) { }

  ngOnInit(): void {
    M.AutoInit();
    this.fieldService.getFields()
      .subscribe(
        res => {
          console.log(res)
          this.fields = res;
        },
        err => console.log(err))
  }
}

I tried declaring const M as any and adding M.AutoInit() in ngOnInit but still not working.


Solution

  • TH JS isue was resolved replacing declare const M: any; with impoert* as M from 'materialize.css/js/materialize.min.js but the carousel stiil didin't work.