【问题标题】:ng-sidebar (Angular 2) implementation issueng-sidebar (Angular 2) 实现问题
【发布时间】:2017-07-12 18:30:40
【问题描述】:

我需要使用 ng-sidebar 在点击标题中的按钮时在左侧显示一个可折叠的侧边栏菜单。

app.component.html

<div class="page-header custom-phead">
    <ng-sidebar-container>
     <ng-sidebar [(opened)]="_opened">
        <p>Sidebar contents</p>
      </ng-sidebar>

<div ng-sidebar-content>
<button (click)="_toggleSidebar()">Toggle</button>
</div>
</ng-sidebar-container>
<form class="heading">
<input type="text" name="search" [(ngModel)]="search"><input type="image" [src]="'../resource/searchicon.png'">
</form>
</div>

而在 app.component.ts 中,

     private _opened: boolean = false;

  private _toggleSidebar() {
    this._opened = !this._opened;
  }

问题是,按钮根本没有反映在屏幕上,此外,没有任何反应。请帮忙解决这个问题。

【问题讨论】:

  • 提供您的app.module.ts。你在那里导入了SidebarModule
  • 是的,我都做到了

标签: javascript angular angular-directive


【解决方案1】:

Andriy 解决方案不适用于 Angular6,因此请在此处添加我的答案。

正如官方文档的ReadME.md 中提到的,您需要提及侧边栏容器的高度元素。

给定的代码对我有用

app.component.html

<div>
    <ng-sidebar-container style=" height: 100vh">
    <ng-sidebar [(opened)]="_opened" mode="push" autoCollapseWidth=100>

      <p>Sidebar contents</p>
      <p>Sidebar contents</p>
      <p>Sidebar contents</p>
      <p>Sidebar contents</p>
      <p>Sidebar contents</p>

    </ng-sidebar>

    <!-- Page content -->
    <div ng-sidebar-content>
      <button (click)="_toggleSidebar()">Toggle sidebar</button>
    </div>

  </ng-sidebar-container>    
</div>

app.component.ts

public _opened: boolean = false;

public _toggleSidebar() {
this._opened = !this._opened;
}

在 app.module.ts 中导入侧边栏为

imports: [
    SidebarModule.forRoot()
]

【讨论】:

  • 漂亮的答案,它帮助我解决了我的问题。谢谢!
【解决方案2】:

尝试将您的 HTML 更改为:

<div class="page-header custom-phead">
  <ng-sidebar-container>
    <ng-sidebar [(opened)]="_opened">
      <p>Sidebar contents</p>
    </ng-sidebar>
    <!-- you can also try to add a div below if your content not visible -->
    <div style="clear:both;"></div>
  </ng-sidebar-container>

  <button (click)="_toggleSidebar()">Toggle</button>

  <form class="heading">
    <input type="text" name="search" [(ngModel)]="search">
    <input type="image" [src]="'../resource/searchicon.png'">
  </form>
</div>

请注意,我从ng-sidebar-container 中取出了&lt;button (click)="_toggleSidebar()"&gt;Toggle&lt;/button&gt;。如果您的侧边栏内容仍然不可见,请尝试在关闭ng-sidebar-container 标签之前添加&lt;div style="clear:both;"&gt;&lt;/div&gt;

我创建了一个plunker,它使用两种方法来切换侧边栏:[(opened)]="_opened"close()open() 函数。它可能会对您的项目有所帮助

【讨论】:

  • 我最初什至尝试过使用 .close() 和 .open()。问题是,我没有看到点击时发生任何活动。ng-sidebar 的内容从未透露过。但是在 .ts 中,函数会在单击按钮时触发返回 true 和 false。
  • 能否请您分享一下 plunker,以便我验证是否遗漏了任何内容?
  • 抱歉,完全忘记分享 plunker 链接:plnkr.co/edit/eP3gOdP4k0ST8rtIWafq?p=preview,我也更新了我的原始答案(添加了 plunker 链接)
  • 作为替代方案,您也可以考虑使用 Material Design 侧边栏 - material.angular.io/components/sidenav/overview
  • 侧边栏根本没有响应
猜你喜欢
  • 1970-01-01
  • 2016-12-20
  • 2017-03-27
  • 2018-10-08
  • 2017-03-20
  • 2018-08-28
  • 2019-02-28
  • 2020-11-07
  • 2017-03-05
相关资源
最近更新 更多