Reputation: 5566
Hi I am creating a responsive navbar using flex box and bem methodology in angular 6, I have added hamburger menu for mobile devices. but its not working here is what I have .
HTML:
<div class="Navbar">
<div class="Navbar__Link Navbar__Link-brand">
Website title
</div>
<div class="Navbar__Link Navbar__Link-toggle">
<i class="fa fa-bars"></i>
</div>
<nav class="Navbar__Items">
<div class="Navbar__Link">
Longer Link
</div>
<div class="Navbar__Link">
Longer Link
</div>
<div class="Navbar__Link">
Link
</div>
</nav>
<nav class="Navbar__Items Navbar__Items--right">
<div class="Navbar__Link">
Link
</div>
<div class="Navbar__Link">
Link
</div>
</nav>
</div>
Here is my full CSS code
body {
margin: 0
}
.Navbar {
background-color: #46ACC2;
display: flex;
padding: 16px;
font-family: sans-serif;
color: white;
}
.Navbar__Link {
padding-right: 8px;
}
.Navbar__Items {
display: flex;
}
.Navbar__Items--right {
margin-left:auto;
}
.Navbar__Link-toggle {
display: none;
}
@media only screen and (max-width: 768px) {
.Navbar__Items,
.Navbar {
flex-direction: column;
}
.Navbar__Items {
display:none;
}
.Navbar__Items--right {
margin-left:0;
}
.Navbar__ToggleShow {
display: flex;
}
.Navbar__Link-toggle {
align-self: flex-end;
display: initial;
position: absolute;
cursor: pointer;
}
}
Here is my js for toggle
function classToggle() {
const navs = document.querySelectorAll('.Navbar__Items')
navs.forEach(nav => nav.classList.toggle('Navbar__ToggleShow'));
}
document.querySelector('.Navbar__Link-toggle').addEventListener('click', classToggle);
and index.html file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Majeni</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script src="./assets/js/toggle.js" type="text/javascript"></script>
</body>
</html>
NOTE
I have created the same navbar in pure html and js everything works fine here is the fiddle to the working one : Menu with Hamburger using BEM and flex Box
But in my angular app When I run the app I get the following error in browser console,
toggle.js:7 Uncaught TypeError: Cannot read property 'addEventListener' of null
what am I doing wrong here?
Upvotes: 0
Views: 1048
Reputation: 27371
In Angular application don't use JQuery or JS native api Angular has a way to handle dom manipulation
Use Directive for Add and remove Class
import { Directive,HostListener,HostBinding } from '@angular/core';
@Directive({
selector: '[appSidebar]',
exportAs:'appSidebar'
})
export class SidebatDirective {
@HostBinding('class.is-open') click=false;
constructor() { }
@HostListener('click') onClic(){
this.click=!this.click;
}
}
Example:https://stackblitz.com/edit/bootstrap-nabar
Upvotes: 2