I want to toggle a sidenav from another component in Angular. I have 3 child Components: menu,content,header. Button is on header component.I want to click on button then menu should toggle.
header.ts
export class HeaderComponent implements OnInit {
constructor(public service: SharedService) {}
ngOnInit() {}
toggleMenu() {
this.service.flag = !this.service.flag;
this.service.flagChange.emit(this.service.flag);
}
}
header.html
<div>
<a href="">
<i class="fas fa-bars text-white barsIcon" ` (click)="toggleMenu()"></i>
</a>
</div>
menu.ts
export class MenuComponent implements OnInit {
constructor(public service: SharedService) {
this.service.flagChange.subscribe((res) => this.service.flag);
}
ngOnInit() {}
}
menu.html
<div>
<ul>
<li>
<a routerLink="/dashboard">Dashboard</a>
</li>
<li>
<a routerLink="/user">User</a>
</li>
<li>
<a routerLink="">Currency</a>
</li>
<li>
<a routerLink="/report">Report</a>
<ul>
<li>
<a routerLink="">Report1</a>
</li>
<li>
<a routerLink="">Report2</a>
</li>
<li>
<a routerLink="">Report3</a>
</li>
</ul>
</li>
</ul>
</div>
service.ts
@Injectable({
providedIn: "root",
})
export class SharedService {
public flag: boolean = false;
public flagChange = new EventEmitter<boolean>();
constructor() {}
}
You aren't that fare, but you should use
BehaviorSubject
and notEventEmitter
for that purposeEmitter a meant for @Output()
here some little changes.
I also refactor a little bit your code ;)
header.ts
header.html
menu.ts
menu.html
service.ts
Error
BehaviorSubject
instead ofEventEmitter
Optimization
Refactoring
:boolean
if you're already adding a value to it, this is implicit.service
ngOnInit
if not usedprivate
if not used in thehtml
file