Angular2 pipeline Pipe and custom pipeline format data usage Example Analysis, angular2pipe

Source: Internet
Author: User
Tags export class

Angular2 pipeline Pipe and custom pipeline format data usage Example Analysis, angular2pipe

This document describes how to use the Pipe of the Angular2 MPs queue and custom MPs queue format data. We will share this with you for your reference. The details are as follows:

Pipeline (Pipe) can format the data according to the developer's wishes, and can also concatenate multiple pipelines.

Pure Pipe and Impure Pipe)

Pipelines are divided into Pure pipelines (Pure Pipe) and non-Pure pipelines (Impure Pipe ). By default, pipelines are pure. When you define a custom pipeline declaration, set the pure flag to false, which is a non-pure pipeline. For example:

@Pipe({ name: 'sexReform', pure:false})

Differences between pure and non-pure pipelines:

① Pure pipe:

Angular performs a pure pipeline only when the input value is checked for a pure change. Pure change refers to the change of the original type value (String, Number, Boolean, Symbol) or the change of the Object Reference (the change of the object value is not a pure change and will not be executed ).

② Non-pure Pipeline

Angular performs non-pure pipelines during the change detection cycle of each component. Therefore, if you use a non-pure pipeline, you must pay attention to performance issues.

Pipeline usage syntax

{{expression | pipe : arg}}

For chained series:

{{expression | pipe1 : arg | pipe2 | pipe3 }}

Common built-in Pipelines

MPs queue Type Function
DatePipe Pure MPs queue Date formatting
JsonPipe Non-pure MPs queue Convert the object to a JSON string using json. stringify ().
UpperCasePipe Pure MPs queue Convert all letters in the text to uppercase letters.
LowerCasePipe Pure MPs queue Convert all letters in the text to lowercase letters.
DecimalPipe Pure MPs queue Value formatting
Currenypipe Pure MPs queue Currency formatting
PercentPipe Pure MPs queue % Formatting
SlicePipe Non-pure MPs queue Array or string Truncation

DatePipe

Syntax:{{expression | date:format}}

Expression supports date objects, date strings, and timestamp in milliseconds. Format is the specified format, common identifier:

Y years y uses four digits to represent the year (2017), and yy uses two digits to represent (17)
M month M 1-digit or two-digit characters (2 or 10, 11, 12), MM two-digit representation, the first fill 0 (02)
D, d, one or two digits (9) dd, two digits, add 0 (09)
E week EEE three-character abbreviation of the day of the week EEEE week full name
J 12-hour system time j (9 AM) jj (09 AM)
H 12-hour h (9) hh (09)
H 24-hour H (9) HH (09)
M: m (5) mm (05)
S second s (1) ss (01)
Z Time Zone z China Standard Time

DecimalPipe

Syntax:{{expression | number[: digiInfo] }}

DigiInfo format:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

That is, the minimum number of digits to be retained. The minimum number of digits to be retained by decimal places-the maximum number of decimal places to be retained

Default: 1.0-3

Currenypipe

Syntax:{{expression | currency[: currencyCode[: symbolDisplay[: digiInfo]]] }}

The format of digiInfo is the same as that of DecimalPipe.

CurrencyCod refers to the currency code. Its value is ISO 4217 standard, CNY, USD, and EUR.
SymbolDisplay is a Boolean value. If it is true, the currency symbol ($) is displayed. If it is false, the currency code is displayed.

PercentPipe

Syntax:{{expression | percent[: digiInfo] }}

The format of digiInfo is the same as that of DecimalPipe.

SlicePipe

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

Expression can be a string or array. String, the pipeline callsString.prototype.slice()Method to intercept substrings. If it is an array, callArray.prototype.slice()Method.

Custom MPs queue

In addition to using built-in pipelines, you can also use custom pipelines to implement more complex functions.

Create an MPS queue:

ng g pipe sexReform

Angular-cli will help us create the SexReformPipe pipeline. This pipeline is used to return Chinese male and female based on male and female.

Code:

Import {Pipe, PipeTransform} from '@ angular/core'; @ Pipe ({name: 'sexreform', // non-pure pipeline pure: false }) export class SexReformPipe implements PipeTransform {transform (value: any, args? : Any): any {let chineseSex; switch (value) {case 'male': chineseSex = 'male'; break; case 'female ': chineseSex = 'female'; break; default: chineseSex = 'unknown gender'; break;} return chineseSex ;}}

The focus is on implementing the PipeTransform interface's transform method, which is defined as a non-pure pipeline for demonstration only. The non-pure pipeline has a great impact on performance and should be avoided as much as possible.

DEMO code

Components:

import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-pipe', templateUrl: './pipe.component.html', styleUrls: ['./pipe.component.css']})export class PipeComponent implements OnInit { date=new Date(); money=5.9372; object={title:'ffff',subTitle:'subtitlefff'}; str='abcdABCD'; percent=0.97989; constructor() { } ngOnInit() { }}

Template:

<p> {{date| date:'y-MM-dd HH:mm:ss'}} <br /> {{object| json }} <br /> {{str| uppercase }} <br /> {{str| lowercase }} <br /> {{money| number:'2.4-10' }} <br /> {{money| number:'5.1-2' }} <br /> {{money| currency:'CNY':false:'1.1-2' }} <br /> {{percent| percent:'1.1-2' }} <br /> {{str| slice:1:3 }} <br /> {{'female'| sexReform }} <br /></p>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.