Search code examples
angularmaterializematerialize-stepper

how to use materialize-stepper with angular


I am using materialize-stepper with angular 6. From the documentation I have to write some HTML and then initialize DOM element like

let stepperInstace = new MStepper(stepper, {
      // options
      firstActive: 0 // this is the default
})

And the HTML

<ul class="stepper linear" #contentTypeStepper>
    <li class="step active">
        <div class="step-title waves-effect">E-mail</div>
        <div class="step-content">
            <!-- Your step content goes here (like inputs or so) -->
            <div class="step-actions">
                <!-- Here goes your actions buttons -->
                <button class="waves-effect waves-dark btn next-step">CONTINUE</button>
            </div>
        </div>
    </li>
    <li class="step">
        <div class="step-title waves-effect">Data</div>
        <div class="step-content">
            <!-- Your step content goes here (like inputs or so) -->
            <div class="step-actions">
                <!-- Here goes your actions buttons -->
                <button class="waves-effect waves-dark btn next-step">CONTINUE</button>
            </div>
        </div>
    </li>
</ul> 

and CSS entry in angular.json

"styles": [
       "node_modules/materialize-stepper/dist/css/mstepper.css"
]

In the ts I am importing it like

import MStepper from "materialize-stepper/dist/js/mstepper";

@ViewChild("contentTypeStepper")
contentTypeStepper: ElementRef;

iContentTypeStepper: any;

and initializing it like

ngAfterViewInit(): void {
    console.log("TCL: AdminContentTypeDetailComponent -> MStepper", MStepper);
    this.iContentTypeStepper = MStepper.constructor(this.contentTypeStepper.nativeElement, {
          firstActive: 0 // this is the default
    });

}

but this is not working. What can be the issue?


Solution

  • This library hasn't been properly modularized which makes it a bit more obtuse to work with. There are posts out there on how to create a .d.ts file for the library in order to use the import syntax for a library like this. I have often found that it is easier to not do that though.

    The easiest way to work with this library in Angular is to make it a 'globally' available library.

    In your angular.json file, make sure you have

    "node_modules/materialize-stepper/dist/css/mstepper.css"
    

    in your scripts property.

    And in your styles property(as you have listed above. Also put

    "node_modules/materialize-stepper/dist/js/mstepper.js"
    

    Then in your ts file, replace

    import MStepper from "materialize-stepper/dist/js/mstepper";
    

    with

    declare const MStepper: any;
    

    With that in place, your above code should work.