6
votes

so i tried to use the solution from here: https://stackoverflow.com/a/48058897/9642
But, that didn't work. I'm using Angular with Typescript, naturally.

My Typescript class:

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, {});
    }

}

On the HTML-Part the Element has the ID 'collabsible', and the Class 'collabsible'. And yet i get this Mistake:

 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

1 Answers

3
votes

You cannot query with@ViewChild by the css id. You need to add the template variable.

So instead of

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

You need to do

<div #collapsible></div>