在Angular中切换侧边栏

我对angular还是比较陌生,我正在尝试使用一项服务来显示和隐藏侧边栏。我显示了侧边栏工作正常,但随后意识到我的侧边栏关闭按钮不是具有切换按钮的父组件的一部分。因此,我认为最好的方法可能是使用服务来控制切换和状态,因为这两个组件都将使用它(潜在的改进令人赞赏)。

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;
    }
}

任何其他可以改进的方式,我都会很高兴地参加,因为现在我可以看到为什么该框架有一个学习曲线。 (所需的任何其他信息,如** k)

评论
  • 柯南
    柯南 回复

    在Angular中,您无法访问模板(HTML)中的私有字段。 我建议将其设置为公共字段,或者使用包装函数。

    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.

    您可以将其更改为get函数:

    public get showSideBar(): boolean {
       return this.navigationService.showSideBar
    }
    

    这样,您仍然可以在模板中访问它而不会出现任何问题。

    这些全都来自内存,所以我可能犯了一个错误,但就我所知,这应该可以解决您的错误问题。