【问题标题】:to write custom pipe for ngFor为 ngFor 编写自定义管道
【发布时间】:2019-09-24 12:04:11
【问题描述】:

我是 angualr 8 的新手,没有使用过自定义管道。请帮助解决这个问题。 如何为 'limitTo:articles.articles.limit 编写自定义管道? article.articles.length : 10'

<div *ngFor="let section_articles of articles.articles | limitTo : articles.articles.limit ? articles.articles.length : 10">

【问题讨论】:

标签: angular


【解决方案1】:

我想你想制作一个只有 10 个项目的可迭代表? 最好在你的方法结束时创建一个.slice(0,10)。 如果不是,您可以按照以下示例参数化管道或对其进行自定义:

import { Pipe, PipeTransform } from '@angular/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 | exponentialStrength:10 }}
 *   formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent?: number): number {
    return Math.pow(value, isNaN(exponent) ? 1 : exponent);
  }
}

例如:使用插值:

<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>

template: `
  <p>The hero's birthday is {{ birthday | date:format }}</p>
  <button (click)="toggleFormat()">Toggle Format</button>
`
export class HeroBirthday2Component {
  birthday = new Date(1988, 3, 15); // April 15, 1988
  toggle = true; // start with true == shortDate

  get format()   { return this.toggle ? 'shortDate' : 'fullDate'; }
  toggleFormat() { this.toggle = !this.toggle; }
}

我从 Angular 文档中得到这个:parameterizing a pipe

【讨论】:

    【解决方案2】:

    解决方案有效:

    <div *ngFor="let section_articles of (articles.articles.limit ? (articles.articles | slice: 0 : articles.articles.length) : (articles.articles | slice: 0 : 10))">
    

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2020-01-24
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      相关资源
      最近更新 更多