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:
Contents
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 casestart
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 casestart
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}}'
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
SourceCode
– Project structure ->
– SourceCode ->