Reputation: 240
I am fairly new to angular and I am trying to use a service to show and hide my sidebar. I had the showing of the sidebar working but then realised that my sidebar close button was not part of the parent component that has the toggle button. So i decided that maybe the best way would be to use a service to control the toggling and state since it will be used by both components (potential improvements much appreciated).
The error I am receiving is : Property 'navigationService' is private and only accessible within class 'AppComponent'.
This can possibly be solved by declaring it as public instead of private but my concern is my toggle button is in the AppComponent, so not sure about the issue(feel like i have gone wrong somewhere).
app.component.html:
<div class="container-fluid">
<div class="row">
<app-sidebar *ngIf="showSideBar; else toggleMenu" class="col-md-2 bg-dark" style="display:block; height: 100vh;"></app-sidebar>
<ng-template #toggleMenu>
<div class="col-md-2"><fa-icon [icon]="faBars" (click)="navigationService.toggleSideBar()" style="cursor: pointer;"></fa-icon></div>
</ng-template>
</div>
</div>
app.component.ts:
import { Component } from '@angular/core';
import{ faBars } from '@fortawesome/free-solid-svg-icons';
import { NavigationService } from './navigation/navigation.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [NavigationService]
})
export class AppComponent {
title = 'my-pmo';
showSideBar: boolean = false;
faBars = faBars;
constructor(private navigationService: NavigationService) {}
}
navigation.service.ts:
export class NavigationService {
showSidebar: boolean = false;
toggleSideBar() {
this.showSidebar = !this.showSidebar;
}
}
Any additional ways this can be improved i will gladly take on board as right now i can see why there is a learning curve to this framework. (any additional info needed, just as**k)
Upvotes: 0
Views: 3119
Reputation: 46
In Angular you can not access private fields in the template (HTML). I would suggest either making it a public field, or use a wrapper function.
export class AppComponent {
title = 'my-pmo';
showSideBar: boolean = false;
faBars = faBars;
constructor(private navigationService: NavigationService) {}
toggleSideBar() {
this.navigationService.toggleSideBar()
}
}
Also, the showSideBar: boolean = false;
you have in your AppComponent.ts won't do anything for you, since it is never set.
You could change this to a get function:
public get showSideBar(): boolean {
return this.navigationService.showSideBar
}
This so you can still access it in your template without any issues.
This is all from memory, so I may have made a mistake, but this should fix the issues that you are having with your error as far as I remember.
Upvotes: 1