Recently delving into Angular and facing a particular challenge: I have created two components, namely header and main. The header contains a toggle button while the main houses the sidenav. My goal is to make the button in the header hide and show the sidenav in the main component upon clicking it. After trying various approaches, it became apparent that using services was necessary due to the components not being directly related as child and parent.
(Toggle.service.ts)
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ToggleService {
choice = true;
toggle() {
this.choice = !this.choice;
}
}
(Header.component.ts)
import { Component, OnInit } from '@angular/core';
import { ToggleService } from '../../services/toggle.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
constructor(private myservice: ToggleService) {
}
ComponentToggleMenu() {
this.myservice.toggle();
}
ngOnInit(): void {
}
(Header.component.html)
<button (click)="ComponentToggleMenu()"><i class="material-icons">menu</i></button>
(Main.component.ts)
import { Component, OnInit } from '@angular/core';
import { ToggleService } from '../../services/toggle.service';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css'],
})
export class MainComponent implements OnInit {
boolean = this.myservice.choice;
constructor(private myservice: ToggleService) {}
ngOnInit(): void {
}
}
(Main.component.html)
<mat-sidenav class="sidenav" mode="side" [opened]="boolean">
Despite my efforts, I haven't been able to get it working perfectly. Deployed the app on Github where you can see the issue for yourself. One important note is that the communication between components seems more complex than anticipated, making it difficult to implement changes smoothly across different components. If you face similar challenges, feel free to check out the repository and deployed version below:
(updated) I didn't fix it, but I made the deploy of the app in the Github and here is the link of the depository and deploy.One detail it's in Portuguese but just click in the toggle button, there is 2 buttons toggle, one in the main component that it's working and the another one in the header component that it's not working. Depository - https://github.com/EltonModellingDesign/Client-Registration-Angular-app Deploy -