为ngFor编写自定义管道

时间:2019-09-24 12:04:11

标签: angular

我是angualr 8的新手,还没有使用自定义管道。请对此提供帮助。 如何为'limitTo:article.articles.limit编写自定义管道? Articles.articles.length:10'

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

2 个答案:

答案 0 :(得分:0)

我想您要制作一个仅包含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; }
}

我从有角度的文档中摘录:parameterizing a pipe

答案 1 :(得分:0)

解决方案:

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