Search code examples
htmlcssangularmaterialize

MaterializeCSS Navbar and Sidenav + Angular 9


So I'm trying to make a dashboard-like Angular app for a school project. I've been making Angular components to modularize the site. So far I have the nav bar and sidenav done, but the side nav is being a bit problematic. I want the side nav to be present on the screen when full size, and collapse when on a smaller screen. When I collapse the screen, the burger menu bars don't open the side nav back up. I don't really understand why this is happening. From what I gather with the docs, I have to initialize the plugin.

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.sidenav');
    var instances = M.Sidenav.init(elems, options);
});

which I have in a script tag at the bottom of the page. I mocked up my code in a Codepen here. It's not "componentized" like it would be in Angular, but it gets the point across. If anyone could help with this I'd appreciate it. Thanks


Solution

  • Remove the undeclared options variable.

    The materialize docs are a little confusing - the javascript initialisation that is listed will actually break your code and it catches a lot of people out. So remove it if you just need the default sidenav functionality.

    document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.sidenav');
        var instances = M.Sidenav.init(elems);
    });
    

    If you do need to pass in any options, then declare it like this:

    document.addEventListener('DOMContentLoaded', function() {
        var options = {
           edge: 'right'
        }
        var elems = document.querySelectorAll('.sidenav');
        var instances = M.Sidenav.init(elems, options);
    });
    

    options is an object - key value pairs for customising the component, a pattern that you'll see all through materialize components. Here are a list of options that can be configured at the point of initialisation. You can position the sidenav on the other side of screen, run functions when it opens, when it closes etc.

    https://materializecss.com/sidenav.html#options

    As a side note - ALWAYS check the console for clues when debugging. This is from your codepen:

    Uncaught ReferenceError: options is not defined at HTMLDocument. (vYOeqEZ:61)

    Also, final note - you mention componentizing. Read this article about using Materialize with React. It will shed light on the subject.

    https://medium.com/@mattdlockyer/youre-using-materialize-css-wrong-470b593e78e9

    You also missed the materialicons cdn, so your icons aren't showing:

    https://materializecss.com/icons.html

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">