【问题标题】:Binding the piped result of an *ngFor to a global variable将 *ngFor 的管道结果绑定到全局变量
【发布时间】:2020-01-07 15:37:34
【问题描述】:
*ngFor="let item of items | filter:{ name: searchString } : searchString as filteredItems"

以后

<button (click)="doSomething(filteredItems)>

filteredItems 只是一个可以在 *ngFor 内部使用的局部变量。如何将filteredItems 绑定到全局变量,以便稍后在按下按钮时提交所有过滤的项目?

【问题讨论】:

  • 我的第二个 pla,&lt;button (click)="doSomething(items | filter:{ name: searchString } : searchString )&gt; 不起作用,因为在操作调用中不允许使用过滤器。
  • 请问您为什么使用管道过滤?对于您想要做的事情,只有一个返回数组的过滤器函数然后将该数组存储为组件的参数不是更容易吗?
  • 我认为过滤管道是可行的方法。我遵循了这样的指南:stackoverflow.com/questions/44769748/angular-4-pipe-filter,效果很好,我只是在项目后期无法获得它的回报。

标签: angular


【解决方案1】:

您可以执行以下操作 `

<ng-container *ngIf=”(items | filter:searchString) as filteredItems”>

  <div *ngFor=”let item of filteredItems”>
    {{item}}
  </div>

  <p>Count: <b>{{filteredItems.length}}</b></p>
  
</ng-container>

那么您将能够使用filteredItems 作为变量。

但是,如果您想在单击按钮时运行某些内容,则不应使用 Pipes,而应在组件中编写函数。

【讨论】:

  • 有效。谢谢!为什么我不应该在这里使用管道?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2013-05-31
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多