Angular built-in Slice Pipe | Array SlicePipe + String SlicePipe Example

angular-built-in-slice-pipe-array-slicepipe-string-slicepipe-example-feature-image

In the tutorial, we show how to work with Angular impure built-in SlicePipe to create a new Array or String containing a subset of the elements.

Related posts:
Angular Built-in KeyValue Pipe
Angular Built-in DatePipe
Angular Custom Pipe | Pure Pipe + Impure Pipe
Angular 6 Service – with Observable Data for Asynchronous Operation

Related pages:

Angular SlicePipe

Syntax:
{{ value_expression | slice : start [ : end ] }}

value: an Array or a String.
start (number): the starting index of the returned subset ->

  • if a positive integer -> return the item at start index and all items after in the list or string expression. In case start is greater than the size of the expression -> an empty list or string is returned
  • if a negative integer -> return the item at start index from the end and all items after in the list or string expression. In case start is greater than the size of the expression -> an empty list or string is returned

end (number): the ending index of the returned subset ->

  • omitted -> all items until the end will be returned
  • if positive -> all items before end index will be returned
  • if negative -> all items before end index from the end will be returned

Practice

SlicePipe with Array and String Example

We create a slice-pipe component as below:
slice-pipe.component.ts ->

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-slice-pipe',
  templateUrl: './slice-pipe.component.html'
})
export class SlicePipeComponent {
  array: string[] = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
  str: string = 'qwertyuopasdfghjkl';
}

slice-pipe.component.html ->

SlicePipe Array

  • {{i}}

SlicePipe String

String's value: {{str}}

slice [0:6]: '{{str | slice:0:6}}'

%MINIFYHTMLcba242fc6397e85b1408f05da4ca35ff16% %MINIFYHTMLcba242fc6397e85b1408f05da4ca35ff17%

slice [6:1]: '{{str | slice:6:1}}' (start > end)

slice [-1]: '{{str | slice:-1}}'

slice [-5]: '{{str | slice:-5}}'

slice [-5:-2]: '{{str | slice:-5:-2}}'

slice [-50]: '{{str | slice:-50}}' (-start < -string.length)

slice [50]: '{{str | slice:50}}' (start > string.length)

Result

angular-built-in-slice-pipe-array-slice-pipe-string-results

SourceCode

– Project structure ->

angular-built-in-slice-pipe-array-slice-pipe-string-project-structure

– SourceCode ->

AngularSlicePipe



By grokonez | September 3, 2018.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*