【问题标题】:How to show/hide in Angular2如何在Angular2中显示/隐藏
【发布时间】:2017-11-02 02:42:42
【问题描述】:

我有一个通过单击按钮显示/隐藏元素的组件。

这是我的html

  <div *ngFor="let history of histories | sortdate: '-dateModified'">
    <p><b>{{ history.remarks }}</b> - <i>{{history.dateModified | date:'short'}}</i></p>
    <a href="google.com" 
    [class.datatable-icon-right]="history.$$expanded" 
    [class.datatable-icon-down]="!history.$$expanded" 
    title="Expand/Collapse Row" 
    (click)="toggleExpandRow(history)"></a>
      <!-- hide/show this by clicking the button above.-->
    <div *ngFor="let step of history.steps; let i = index">
      <b>{{i+1}}.</b> {{step}}
      <span class="clear"></span>
    </div>
    <hr />
  </div>

还有我的.ts

  toggleExpandRow(row) {
    console.log('Toggled Expand Row!', row);
    //row
    return false;
  }

尝试搜索,但找不到任何相同的样本。

在 jquery 上,我可以做到这一点,但在 Angular2 上,我很难做到这一点。

【问题讨论】:

  • 你想隐藏哪个元素?使用 ngIf 指令
  • 我想显示/隐藏这个&lt;div [hidden]="!history.$$expanded" *ngFor="let step of history.steps; let i = index"&gt;
  • 将其包装在&lt;ng-container ngIf="shown"&gt;... 中,将shown 属性添加到组件并在toggleExpandRow 中切换它
  • 可能是你从这个堆栈答案中得到你的答案:stackoverflow.com/questions/35163009/…
  • 但是,它是关于按行显示/隐藏。不隐藏/显示所有数据。

标签: html angular


【解决方案1】:

有两种选择:

1- 你可以使用 hidden 指令来显示或隐藏任何元素

<div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
  <strong>List Saved!</strong> Your changes has been saved.
</div>

2- 您可以使用 ngIf 控制指令来添加或删除元素。这与 hidden 指令不同,因为它不显示/隐藏元素,而是从 DOM 中添加/删除。您可以丢失元素的未保存数据。对于被取消的编辑组件,它可能是更好的选择。

<div *ngIf="edited" class="alert alert-success box-msg" role="alert"> 
  <strong>List Saved!</strong> Your changes has been saved.
</div>

【讨论】:

【解决方案2】:

在重复的行中使用ngIf。创建一个名为showStep 的布尔属性来指示该行是否应该展开。

<div *ngFor="let step of history.steps; let i = index" ngIf="history.showStep">
  <b>{{i+1}}.</b> {{step}}
  <span class="clear"></span>
</div>

然后,在您的 .ts 文件中:

  toggleExpandRow(history) {
     history.showStep = !history.showStep
     //note the same porperty of showStep that is used in your html
  }

额外:

其实,为了节省几行代码,你甚至根本不需要toggleExpandRow 函数。您可以在 html 中内联:

//other attributes omitted for brevity
<a (click)="history.showStep = !history.showStep">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    相关资源
    最近更新 更多