खोज…


परिचय

पाइप | चरित्र का उपयोग कोणीय 2 में पाइपों को लागू करने के लिए किया जाता है। पाइप्स को AngularJS में फिल्टर के समान होते हैं जिसमें वे दोनों डेटा को एक निर्दिष्ट प्रारूप में बदलने में मदद करते हैं।

पैरामीटर

समारोह / पैरामीटर व्याख्या
@ पिप ({नाम, शुद्ध}) पाइप के लिए मेटाडेटा, तुरंत पाइप क्लास से पहले होना चाहिए
नाम: स्ट्रिंग आप टेम्पलेट के अंदर क्या उपयोग करेंगे
शुद्ध: बूलियन सत्य के लिए चूक, अपने पाइप को अधिक बार मूल्यांकन करने के लिए इसे गलत के रूप में चिह्नित करें
परिवर्तन (मूल्य, args []?) फ़ंक्शन जिसे टेम्पलेट में मानों को बदलने के लिए कहा जाता है
मूल्य: कोई भी वह मान जिसे आप बदलना चाहते हैं
अर्ग: कोई [] आपके रूपांतरण में जिन तर्कों की आवश्यकता हो सकती है, वे शामिल हैं। वैकल्पिक वैकल्पिक निशान के साथ? ऑपरेटर जैसे ट्रांसफ़ॉर्म (मान, arg1, arg2?)

टिप्पणियों

यह विषय Angular2 पाइप्स को कवर करता है , जो कि Angular2 एप्लिकेशन में HTML टेम्प्लेट के भीतर डेटा को रूपांतरित करने और प्रारूपित करने के लिए एक तंत्र है।

चेनिंग पाइप्स

पाइपों की जंजीर हो सकती है।

<p>Today is {{ today | date:'fullDate' | uppercase}}.</p>

कस्टम पाइप

my.pipe.ts

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

@Pipe({name: 'myPipe'})
export class MyPipe implements PipeTransform {

  transform(value:any, args?: any):string {
    let transformedValue = value; // implement your transformation logic here
    return transformedValue;
  }

}

my.component.ts

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

@Component({
  selector: 'my-component',
  template: `{{ value | myPipe }}`
})
export class MyComponent {

    public value:any;

}

my.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { MyComponent } from './my.component';
import { MyPipe } from './my.pipe';

@NgModule({
  imports: [
    BrowserModule,
  ],
  declarations: [
    MyComponent,
    MyPipe
  ],
})
export class MyModule { }

बिल्ट-इन पाइप्स

Angular2 कुछ अंतर्निहित पाइपों के साथ आता है:

पाइप प्रयोग उदाहरण
DatePipe date {{ dateObj | date }} // output is 'Jun 15, 2015'
UpperCasePipe uppercase {{ value | uppercase }} // output is 'SOMETEXT'
LowerCasePipe lowercase {{ value | lowercase }} // output is 'sometext'
CurrencyPipe currency {{ 31.00 | currency:'USD':true }} // output is '$31'
PercentPipe percent {{ 0.03 | percent }} //output is %3

और भी हैं। उनके प्रलेखन के लिए यहां देखें।

उदाहरण

होटल-reservation.component.ts

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

@Component({
    moduleId: module.id,
    selector: 'hotel-reservation',
    templateUrl: './hotel-reservation.template.html'
})
export class HotelReservationComponent {
    public fName: string =  'Joe';
    public lName: string = 'SCHMO';
    public reservationMade: string = '2016-06-22T07:18-08:00'
    public reservationFor: string = '2025-11-14';
    public cost: number = 99.99;
}

होटल-reservation.template.html

<div>
    <h1>Welcome back {{fName | uppercase}} {{lName | lowercase}}</h1>
    <p>
        On {reservationMade | date} at {reservationMade | date:'shortTime'} you 
        reserved room 205 for {reservationDate | date} for a total cost of 
        {cost | currency}.
    </p>
</div>

उत्पादन

Welcome back JOE schmo
On Jun 26, 2016 at 7:18 you reserved room 205 for Nov 14, 2025 for a total cost of 
$99.99.

JsonPipe के साथ डिबगिंग

JsonPipe का उपयोग किसी भी आंतरिक की स्थिति को डीबग करने के लिए किया जा सकता है।

कोड

@Component({
  selector: 'json-example',
  template: `<div>
    <p>Without JSON pipe:</p>
    <pre>{{object}}</pre>
    <p>With JSON pipe:</p>
    <pre>{{object | json}}</pre>
  </div>`
})
export class JsonPipeExample {
  object: Object = {foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}};
}

उत्पादन

Without JSON Pipe:
object
With JSON pipe:
{object:{foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}}

विश्व स्तर पर उपलब्ध कस्टम पाइप

एक कस्टम पाइप उपलब्ध अनुप्रयोग को चौड़ा करने के लिए, एप्लिकेशन बूटस्ट्रैप के दौरान, PLATFORM_PIPES का विस्तार करना।

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { provide, PLATFORM_PIPES } from '@angular/core';

import { AppComponent } from './app.component';
import { MyPipe } from './my.pipe'; // your custom pipe

bootstrap(AppComponent, [
  provide(PLATFORM_PIPES, {
            useValue: [
                MyPipe 
            ],
            multi: true
        })
]);

यहाँ ट्यूटोरियल: https://scotch.io/tutorials/create-a-globally-available-custom-pipe-in-angular-2

कस्टम पाइप बनाना

एप्लिकेशन / pipes.pipe.ts

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

@Pipe({name: 'truthy'})
export class Truthy implements PipeTransform {
  transform(value: any, truthy: string, falsey: string): any {
    if (typeof value === 'boolean'){return value ? truthy : falsey;}
    else return value
  }
}

एप्लिकेशन / मेरी-component.component.ts

import { Truthy} from './pipes.pipe';

@Component({
  selector: 'my-component',
  template: `
    <p>{{value | truthy:'enabled':'disabled' }}</p>
  `,
  pipes: [Truthy]
})
export class MyComponent{ }

Async मानों को Async पाइप से अनप्लग करें

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Component({
  selector: 'async-stuff',
  template: `
    <h1>Hello, {{ name | async }}</h1>
    Your Friends are:
    <ul>
      <li *ngFor="let friend of friends | async">
        {{friend}}
      </li>
    </ul>
  `
})
class AsyncStuffComponent {
  name = Promise.resolve('Misko');
  friends = Observable.of(['Igor']);
}

हो जाता है:

<h1>Hello, Misko</h1>
Your Friends are:
<ul>
  <li>
    Igor
  </li>
</ul>

मौजूदा पाइप का विस्तार

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


@Pipe({name: 'ifDate'})
export class IfDate implements PipeTransform {
  private datePipe: DatePipe = new DatePipe();

  transform(value: any, pattern?:string) : any {
    if (typeof value === 'number') {return value}
    try {
      return this.datePipe.transform(value, pattern)
    } catch(err) {
      return value
    }
  }
}

स्टेटफुल पाइप्स

कोणीय 2 दो अलग-अलग प्रकार के पाइप प्रदान करता है - स्टेटलेस और स्टेटफुल। डिफ़ॉल्ट रूप से पाइप स्टेटलेस होते हैं। हालांकि, हम pure संपत्ति को false स्थापित करके स्टेटफुल पाइप को लागू कर सकते हैं। जैसा कि आप पैरामीटर अनुभाग में देख सकते हैं, आप एक name निर्दिष्ट कर सकते हैं और घोषणा कर सकते हैं कि पाइप शुद्ध होना चाहिए या नहीं, जिसका अर्थ स्टेटफुल या स्टेटलेस है। जबकि डेटा एक स्टेटलेस पाइप (जो एक शुद्ध कार्य है) के माध्यम से बहता है जो कुछ भी याद नहीं करता है , डेटा को प्रबंधित किया जा सकता है और स्टेटफुल पाइप द्वारा याद किया जा सकता है। स्टेटफुल पाइप का एक अच्छा उदाहरण AsyncPipe जो कोणीय 2 द्वारा प्रदान किया गया है।

महत्वपूर्ण

ध्यान दें कि अधिकांश पाइप को स्टेटलेस पाइप की श्रेणी में आना चाहिए। प्रदर्शन कारणों से यह महत्वपूर्ण है क्योंकि एंगुलर परिवर्तन डिटेक्टर के लिए स्टेटलेस पाइप का अनुकूलन कर सकता है। इसलिए सावधानी से स्टेटफुल पाइप का उपयोग करें। सामान्य तौर पर, कोणीय 2 में पाइपों के अनुकूलन से कोणीय 1.x में फिल्टर पर एक प्रमुख प्रदर्शन वृद्धि होती है। कोणीय 1 में डाइजेस्ट चक्र को हमेशा सभी फ़िल्टर को फिर से चलाना पड़ता था, भले ही डेटा बिल्कुल भी नहीं बदला हो। कोणीय 2 में, एक बार एक पाइप के मूल्य की गणना की जाने के बाद, परिवर्तन डिटेक्टर इस पाइप को फिर से नहीं चलाना जानता है जब तक कि इनपुट में परिवर्तन न हो।

एक राज्य पाइप का कार्यान्वयन

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

@Pipe({
  name: 'countdown',
  pure: false
})
export class CountdownPipe implements PipeTransform, OnDestroy  {
  private interval: any;
  private remainingTime: number;

  transform(value: number, interval: number = 1000): number {
    if (!parseInt(value, 10)) {
      return null;
    }
    
    if (typeof this.remainingTime !== 'number') {
      this.remainingTime = parseInt(value, 10);
    }
    
    if (!this.interval) {
      this.interval = setInterval(() => {
        this.remainingTime--;
        
        if (this.remainingTime <= 0) {
          this.remainingTime = 0;
          clearInterval(this.interval);
          delete this.interval;
        }
      }, interval);
    }
    
    return this.remainingTime;
  }
  
  ngOnDestroy(): void {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }
}

आप हमेशा की तरह पाइप का उपयोग कर सकते हैं:

{{ 1000 | countdown:50 }}
{{ 300 | countdown }}

यह महत्वपूर्ण है कि आपका पाइप भी OnDestroy इंटरफ़ेस को लागू करता है ताकि आप अपने पाइप के नष्ट हो जाने पर सफाई कर सकें। उपरोक्त उदाहरण में, मेमोरी लीक से बचने के लिए अंतराल को साफ करना आवश्यक है।

गतिशील पाइप

मामले के परिदृश्य का उपयोग करें: एक तालिका दृश्य में अलग-अलग डेटा प्रारूप वाले अलग-अलग कॉलम होते हैं जिन्हें अलग-अलग पाइपों से बदलना पड़ता है।

table.component.ts

...
import { DYNAMIC_PIPES } from '../pipes/dynamic.pipe.ts';

@Component({
    ...
    pipes: [DYNAMIC_PIPES]
})
export class TableComponent {
    ...

    // pipes to be used for each column
    table.pipes = [ null, null, null, 'humanizeDate', 'statusFromBoolean' ],
    table.header = [ 'id', 'title', 'url', 'created', 'status' ],
    table.rows = [
        [ 1, 'Home', 'home', '2016-08-27T17:48:32', true ],
        [ 2, 'About Us', 'about', '2016-08-28T08:42:09', true ],
        [ 4, 'Contact Us', 'contact', '2016-08-28T13:28:18', false ],
        ...
    ]
    ...

}

dynamic.pipe.ts

import {
    Pipe,
    PipeTransform
} from '@angular/core';
// Library used to humanize a date in this example
import * as moment from 'moment';

@Pipe({name: 'dynamic'})
export class DynamicPipe implements PipeTransform {

    transform(value:string, modifier:string) {
        if (!modifier) return value;
        // Evaluate pipe string
        return eval('this.' + modifier + '(\'' + value + '\')')
    }

    // Returns 'enabled' or 'disabled' based on input value
    statusFromBoolean(value:string):string {
        switch (value) {
            case 'true':
            case '1':
                return 'enabled';
            default:
                return 'disabled';
        }
    }

    // Returns a human friendly time format e.g: '14 minutes ago', 'yesterday'
    humanizeDate(value:string):string {
        // Humanize if date difference is within a week from now else returns 'December 20, 2016' format
        if (moment().diff(moment(value), 'days') < 8) return moment(value).fromNow();
        return moment(value).format('MMMM Do YYYY');
    }
}

export const DYNAMIC_PIPES = [DynamicPipe];

table.component.html

<table>
    <thead>
        <td *ngFor="let head of data.header">{{ head }}</td>
    </thead>
    <tr *ngFor="let row of table.rows; let i = index">
        <td *ngFor="let column of row">{{ column | dynamic:table.pipes[i] }}</td>
    </tr>
</table>

परिणाम

| ID | Page Title     | Page URL    | Created          | Status     |
---------------------------------------------------------------------
|  1 | Home           | home        | 4 minutes ago    | Enabled    |
|  2 | About Us       | about       | Yesterday        | Enabled    |
|  4 | Contact Us     | contact     | Yesterday        | Disabled   |
---------------------------------------------------------------------

एक पाइप का परीक्षण

एक पाइप को देखते हुए जो एक स्ट्रिंग को उल्टा करता है

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

@Pipe({ name: 'reverse' })
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}

यह इस तरह से कल्पना फ़ाइल को कॉन्फ़िगर करने का परीक्षण किया जा सकता है

import { TestBed, inject } from '@angular/core/testing';

import { ReversePipe } from './reverse.pipe';

describe('ReversePipe', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ReversePipe],
    });
  });

  it('should be created', inject([ReversePipe], (reversePipe: ReversePipe) => {
    expect(reversePipe).toBeTruthy();
  }));

  it('should reverse a string', inject([ReversePipe], (reversePipe: ReversePipe) => {
    expect(reversePipe.transform('abc')).toEqual('cba');
  }));
});


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow