수색…


소개

파이프 | 문자는 Angular 2로 파이프를 적용하는 데 사용됩니다. 파이프는 AngularJS의 필터와 매우 유사하므로 데이터를 지정된 형식으로 변환하는 데 도움이됩니다.

매개 변수

함수 / 매개 변수 설명
@ 파이프 ({이름, 순수}) 파이프의 메타 데이터는 파이프 클래스 바로 앞에 있어야합니다.
이름 : 문자열 템플릿 내에서 사용할 것은 무엇입니까?
순수 : 부울 기본값은 true로, 파이프를 더 자주 평가하게하려면 false로 표시합니다.
변환 (값, args []?) 템플릿의 값을 변환하기 위해 호출되는 함수
값 : 임의 변환하고 싶은 값
args : 모든 [] 변환에 필요한 인수가 필요할 수 있습니다. 선택적 args에?를 표시 하시겠습니까? 연산자가 그렇게 좋아요 transform (value, arg1, arg2?)

비고

이 항목에서는 Angular2 응용 프로그램에서 HTML 템플릿 내의 데이터를 변형하고 서식을 지정하기위한 메커니즘 인 Angular2 Pipe를 다룹니다.

연결 파이프

파이프가 얽혀있을 수 있습니다.

<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

다른 것들도 있습니다. 여기 에 그들의 문서를보십시오.

hotel-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;
}

hotel-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

사용자 지정 파이프 만들기

app / 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
  }
}

app / my-component.component.ts

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

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

비동기 파이프로 비동기 값의 랩핑 해제

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
    }
  }
}

스테이트 풀 파이프

Angular 2는 두 가지 유형의 파이프 (상태 비 저장 및 상태 저장)를 제공합니다. 파이프는 기본적으로 상태 비 저장됩니다. 그러나 pure 속성을 false 로 설정하여 상태 파이프를 구현할 수 있습니다. 매개 변수 섹션에서 볼 수 있듯이 name 지정하고 파이프가 순수한지 여부, 즉 상태 저장 또는 상태 비 저장을 의미 할 수 있는지 여부를 선언 할 수 있습니다. 데이터가 기억 되지 않는 상태없는 파이프 (순수 함수 임)를 통해 데이터가 흐르지 만 데이터는 상태 저장 파이프에 의해 관리되고 기억 될 수 있습니다. 상태 유지 파이프의 좋은 예는 앵귤러 2에 의해 제공되는 AsyncPipe 입니다.

중대한

대부분의 파이프는 상태 비 저장 파이프 범주에 속해야합니다. Angular가 변경 감지기의 상태 비 저장 파이프를 최적화 할 수 있기 때문에 이는 성능상의 이유로 중요합니다. 따라서 상태있는 파이프를 신중하게 사용하십시오. 일반적으로 Angular 2의 파이프 최적화는 Angular 1.x의 필터보다 성능이 크게 향상되었습니다. Angular 1에서는 데이터가 전혀 변경되지 않았더라도 항상 다이제스트주기가 모든 필터를 다시 실행해야했습니다. Angular 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('');
  }
}

다음과 같이 spec 파일을 테스트하여 테스트 할 수 있습니다.

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