Materialize中的M是未定义的,角度9

时间:2020-05-11 21:23:13

标签: javascript angular typescript materialize

我将Materialize添加到Angular 9应用程序中。大多数元素以正确的方式显示,但是其中一些元素需要初始化。根据文档,此操作的默认方法如下:

   ngOnInit() {
  const elem = document.querySelector('.tabs');
  const options= {};
  M.Tabs.init(elem, options);
}

当我为自己的代码实现此功能时,Angular会编译,但在运行时会引发错误:M未定义。我将在下面分享相关的代码段。

标头组件

import {AfterViewInit, Component, OnInit} from '@angular/core';
import * as M from 'materialize-css/dist/js/materialize';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']

})
export class HeaderComponent implements OnInit, AfterViewInit {
  options = {};

  constructor() { }

  ngOnInit(): void {
    const elems = document.querySelector('.sidenav');
    const instances = M.Sidenav.init(elems, this.options);
  }
  ngAfterViewInit(): void {
  }
}

组件的模板

<nav class="white" role="navigation">
<div class="nav-wrapper">
  <a href="#!" class="brand-logo black-text">You-Coach</a>
  <ul class="right hide-on-med-and-down">
    <li ><a  class="black-text" translate>menu.link.home</a></li>
    <li ><a  class="black-text" translate>menu.link.about-us</a></li>
    <li><a  class="black-text" translate>menu.link.contact</a></li>
    <li><a class="waves-effect waves-light yellow darken-2 btn black-text" translate>menu.button.sign-in<i
      class="material-icons right">person</i></a></li>
    <li><a class="waves-effect waves-light teal lighten-3 btn black-text" translate>menu.button.register<i
      class="material-icons right">person_add</i></a></li>

  </ul>

  <ul id="nav-mobile" class="sidenav">
    <li><a href="#">Home</a></li>
    <li><a href="#">About us</a></li>
    <li><a href="#">Contact</a></li>
    <li><a class="waves-effect waves-light yellow darken-2 btn black-text">Sign in<i
      class="material-icons right">person</i></a></li>
    <li><a class="waves-effect waves-light teal lighten-3 btn black-text">Register<i
      class="material-icons right">person_add</i></a></li>
  </ul>
  <a href="#" data-target="nav-mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a>

package.json

 "dependencies": {
"@angular/animations": "^9.1.6",
"@angular/common": "~9.1.4",
"@angular/compiler": "~9.1.4",
"@angular/core": "~9.1.4",
"@angular/forms": "~9.1.4",
"@angular/localize": "~9.1.4",
"@angular/platform-browser": "~9.1.4",
"@angular/platform-browser-dynamic": "~9.1.4",
"@angular/router": "~9.1.4",
"@mdi/font": "^5.1.45",
"@ngx-translate/core": "^12.1.2",
"@ngx-translate/http-loader": "^4.0.0",
"angular2-materialize": "^15.1.10",
"ngx-materialize": "^6.1.3",
"rxjs": "~6.5.5"}

谢谢!

0 个答案:

没有答案