【问题标题】:Get DOM elements quantity in Angular(4) application在 Angular(4) 应用程序中获取 DOM 元素数量
【发布时间】:2017-11-22 19:57:53
【问题描述】:

我正在使用 Angular 开发应用程序。

我会显示来自通知数组的通知。它们来自套接字连接。

<div class="notifications-container">
  <div *ngFor='let notification of notifications'>

        <div class="notification-messege" title="{{notification.body.content}}">
            {{notification.body.content}}
        </div>

    </div>
  </div>

如果通知超过 5 个,我该如何隐藏?

【问题讨论】:

  • 要隐藏notification-messege 吗?
  • 下面的一些答案显示了使用 *ngIf 的解决方案。如果是我,我会创建一个仅包含 5 个项目的第二个过滤数组。然后我将我的模板绑定到那个过滤后的数组。
  • notifications | slice: 0: 5

标签: html angular typescript dom socket.io


【解决方案1】:

如果您要显示前 5 个通知。你可以使用 index 和 *ngIf。

<div class="notifications-container">
  <div *ngFor='let notification of notifications; let i = index'>

        <div *ngIf = "i<5" class="notification-messege" title="{{notification.body.content}}">
            {{notification.body.content}}
        </div>

    </div>
  </div>

使用slice pipe

<div class="notifications-container">
  <div *ngFor='let notification of notifications | slice:0:5;'>

        <div class="notification-messege" title="{{notification.body.content}}">
            {{notification.body.content}}
        </div>

    </div>
  </div>

显示最后五个通知:

<div class="notifications-container">
      <div *ngFor='let notification of (notifications | slice:notifications.lenght- 5)'>    
            <div class="notification-messege" title="{{notification.body.content}}">
                {{notification.body.content}}
            </div>    
        </div>
   </div>

【讨论】:

  • 它显示前 5 个项目,但我想显示最后 5 个项目
  • 只获取最后五个元素的子集
  • 更新了答案以显示最后五个通知。你是什​​么意思我的反之亦然?举个例子吧。
【解决方案2】:

您可以使用 Angular 的 *ngIf 指令来限制要显示的通知。

修改你的代码如下:

<div class="notifications-container">
  <div *ngFor='let notification of notifications'>

        <div *ngIf="noitications.length<=5" class="notification-messege" title="{{notification.body.content}}">
            {{notification.body.content}}
        </div>

    </div>
</div>

注意*ngIf="noitications.length&lt;=5",这里如果notifications数组中存储的通知数量大于5则notification-message将不会显示。

【讨论】:

  • 它显示前 5 个项目,但我想显示最后 5 个项目
猜你喜欢
相关资源
最近更新 更多
热门标签