Search code examples
angularmaterialize

how to implement materialize navbar with angular 8


I am new to angular and I have added materialize framework to my angular application by

npm install materialize-css --save 
npm install jquery --save
npm install --save hammerjs

my question is how can I implement materialize navbar in angular? what I have tried until now is:

<ul id="dropdown1" class="dropdown-content">
    <li><a href="#!">one</a></li>
    <li><a href="#!">two</a></li>
    <li class="divider"></li>
    <li><a href="#!">three</a></li>
  </ul>
  <nav>
    <div class="nav-wrapper">
      <a href="#!" class="brand-logo">Logo</a>
      <ul class="right hide-on-med-and-down">
        <li><a href="sass.html">Sass</a></li>
        <li><a href="badges.html">Components</a></li>
        <!-- Dropdown Trigger -->
        <li><a class="dropdown-trigger" href="#!" data-target="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a></li>
      </ul>
    </div>
  </nav>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    var elems = document.querySelectorAll('.dropdown-trigger');
    var instances = M.Dropdown.init(elems, options);
  });

</script>

but it does not work, I have also tried jquery like this

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src="js/materialize.min.js"></script>
  <script>
    $(document).ready(function () {
$(".dropdown-trigger").dropdown();

    });
  </script>

Solution

  • I would suggest to use Angular Material.

    In the components section you can find several material components like the menu which can be used as main nav bar.

    A minimal example would look like this:

    <mat-menu #appMenu="matMenu">
      <button mat-menu-item>Settings</button>
      <button mat-menu-item>Help</button>
    </mat-menu>
    
    <button mat-icon-button [matMenuTriggerFor]="appMenu">
      <mat-icon>more_vert</mat-icon>
    </button>
    

    Have a look at the examples for Menu to get some ideas:

    https://material.angular.io/components/menu/examples

    Additionally you can make use of several starter repos to see how Angular works together with Material e.g. angular-ngrx-material-starter


    If you insist to use to use materializecss can make use of 'AfterViewInit' of angular to initialize elements. In your 'ts' file, implement 'AfterViewInit' and override ngAfterViewInit() method. Then write your initialization code inside setTimeout() function inside ngAfterViewInit().

    export class NameComponent implements OnInit, AfterViewInit {
      ....
    
      ngAfterViewInit(): void {
        setTimeout( function() {
          var elem = document.querySelector('.sidenav');
          var instance = M.Sidenav.init(elem, options);
        }, 0)
      }
    
      .....
    
    }