简体   繁体   English

Angular 6,Materialize:初始化javascript

[英]Angular 6, Materialize: initializing javascript

I am new to Angular and Materialize.我是 Angular 和 Materialise 的新手。 I am trying to initialize a carousel within my Angular component.我正在尝试在我的 Angular 组件中初始化一个轮播。

Materialize mentions three ways: Materialise 提到了三种方式:

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.我已经通过节点安装了 Materialise。 I have both its CSS and JS as dependencies in my angular.json folder.我的 angular.json 文件夹中有它的 CSS 和 JS 作为依赖项。 The CSS styling works. CSS 样式有效。 I have tried these three methods within my ngOnInit lifecycle hook within my component.我在组件中的ngOnInit生命周期钩子中尝试了这三种方法。 "M" is not recognized.无法识别“M”。 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.然后我将 jquery 安装为依赖项并尝试了该方法,但这似乎也不起作用。

You should use the Materialize for Angular library.您应该使用 Materialize for Angular 库。 Asking how to use jQuery with Angular can get you a lot of downvotes.询问如何在 Angular 中使用 jQuery 可能会得到很多反对。

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

  • import OnInit from @angular/core library@angular/core库导入OnInit

  • declare const M: any; underneath imports在进口之下

  • fire the M.AutoInit() function in ngOnInit() lifecycle hookngOnInit()生命周期钩子中ngOnInit() M.AutoInit()函数

Example (where the component name is MediaComponent):示例(其中组件名称为 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';从“@angular/core”导入 { Component, OnInit }; declare var M: any;声明 var M: any;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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