在Angular 5中使用materialize-css(v 1.0.0)不起作用

时间:2018-04-16 08:05:54

标签: angular typescript materialize

所以我尝试使用此处的解决方案:https://stackoverflow.com/a/48058897/9642
但是,这没有用。我自然而然地使用Angular和Typescript。

我的Typescript类:

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import * as M from 'materialize-css/dist/js/materialize';

@Component({
    selector: 'app-list-nav',
    templateUrl: './list-nav.component.html',
    styleUrls: ['./list-nav.component.css']
})
export class ListNavComponent implements OnInit, AfterViewInit {

    @ViewChild('collapsible') elCollapsible: ElementRef;

    constructor() { }

    ngOnInit() {

    }

    ngAfterViewInit() {
        const instanceCollapsible = new M.Collapsible(this.elCollapsible.nativeElement, {});
    }

}

在HTML-Part上,Element的ID为'collabsible',Class为'collabsible'。 然而我得到了这个错误:

 ng:///AppModule/ContentComponent.ngfactory.js:12 ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at ListNavComponent.ngAfterViewInit (webpack-internal:///../../../../../src/app/list-nav/list-nav.component.ts:20)
    at callProviderLifecycles (webpack-internal:///../../../core/esm5/core.js:12922)
    at callElementProvidersLifecycles (webpack-internal:///../../../core/esm5/core.js:12889)
    at callLifecycleHooksChildrenFirst (webpack-internal:///../../../core/esm5/core.js:12872)
    at checkAndUpdateView (webpack-internal:///../../../core/esm5/core.js:14027)
    at callViewAction (webpack-internal:///../../../core/esm5/core.js:14369)
    at execComponentViewsAction (webpack-internal:///../../../core/esm5/core.js:14301)
    at checkAndUpdateView (webpack-internal:///../../../core/esm5/core.js:14024)
    at callViewAction (webpack-internal:///../../../core/esm5/core.js:14369)
    at execEmbeddedViewsAction (webpack-internal:///../../../core/esm5/core.js:14327)

1 个答案:

答案 0 :(得分:1)

您无法通过css ID查询@ViewChild。您需要添加模板变量。

所以而不是

<div id="collapsible"></div>

你需要做

<div #collapsible></div>