【问题标题】:Is there any alternative for "limitTo" in Angular2 or plusAngular2中的“limitTo”是否有任何替代方案或加号
【发布时间】:2019-03-04 06:46:35
【问题描述】:

与 Angularjs (Angular-1) 一样,有一个 limitTo 过滤器 来限制您必须显示的文本

例如:如果我有一个像

这样的字符串
$scope.val = "hey there how are you";

我必须在 HTML 端只显示有限的文本,所以我使用了

{{val | limiteTo:10}}

所以它只显示字符串中的 10 个字符,例如 :: hey there

我在 Angualr2 上移动了,我不知道如何在这里完成,我使用了相同的过滤器但它不起作用

【问题讨论】:

  • 切片管道是可行的方法,检查demo here
  • 感谢@PankajParkar 的作品

标签: angularjs angular angular2-template angular2-directives


【解决方案1】:

使用 SlicePipe

创建一个新的数组或字符串,其中包含一个子集(切片) 元素。

@Component({
  selector: 'slice-string-pipe',
  template: `<div>
    <p>{{str}}[0:4]: '{{str | slice:0:4}}' - output is expected to be 'abcd'</p>
    <p>{{str}}[4:0]: '{{str | slice:4:0}}' - output is expected to be ''</p>
    <p>{{str}}[-4]: '{{str | slice:-4}}' - output is expected to be 'ghij'</p>
    <p>{{str}}[-4:-2]: '{{str | slice:-4:-2}}' - output is expected to be 'gh'</p>
    <p>{{str}}[-100]: '{{str | slice:-100}}' - output is expected to be 'abcdefghij'</p>
    <p>{{str}}[100]: '{{str | slice:100}}' - output is expected to be ''</p>
  </div>`
})
export class SlicePipeStringComponent {
  str: string = 'abcdefghij';
}

或者创建自定义管道

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'slice'
})
export class SlicePipe implements PipeTransform {
  transform(value: any, start?: any, end?: any): any {
    if (start == null && end == null) {
      return value;
    }
    else {
      return value.slice(start, end);
    }
  }

}

例如:https://stackblitz.com/edit/angular-uv5gvs

参考:https://angular.io/api/common/SlicePipe

【讨论】:

    【解决方案2】:

    Angular 4 中有切片管道,你可以使用它,下面是 tutorialspoint.com 的代码 sn-p,下面我也附上了一个链接。

    <div style="width:40%;float:left;border:solid 1px black;">
      <h1>Json Pipe</h1>
      <b>{{ jsonval | json }}</b>
      <h1>Percent Pipe</h1>
      <b>{{00.54565 | percent}}</b>
      <h1>Slice Pipe</h1>
      <b>{{months | slice:2:6}}</b> // here 2 and 6 refers to the start and the end index
    </div>

    Angular 4 pipes

    Built in pipes Angular

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2017-03-06
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2011-06-07
      • 2012-05-03
      • 2020-04-14
      • 2019-06-16
      相关资源
      最近更新 更多