여러 개의 인수가있는 Angular 2 파이프를 어떻게 호출합니까?
다음과 같이 파이프를 호출 할 수 있다는 것을 알고 있습니다.
{{ myData | date:'fullDate' }}
여기서 날짜 파이프는 하나의 인수 만 취합니다. 컴포넌트의 템플릿 HTML에서 직접 코드로 더 많은 파라미터를 가진 파이프를 호출하는 구문은 무엇입니까?
구성 요소 템플릿에서 콜론으로 구분하여 여러 인수를 사용할 수 있습니다.
{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}
코드에서 다음과 같이 보일 것입니다.
new MyPipe().transform(myData, arg1, arg2, arg3)
파이프 내부의 변환 함수에서 다음과 같은 인수를 사용할 수 있습니다.
export class MyPipe implements PipeTransform {
// specify every argument individually
transform(value: any, arg1: any, arg2: any, arg3: any): any { }
// or use a rest parameter
transform(value: any, ...args: any[]): any { }
}
베타 16 이전 (2016-04-26)
파이프는 모든 인수를 포함하는 배열을 취하므로 다음과 같이 호출해야합니다.
new MyPipe().transform(myData, [arg1, arg2, arg3...])
그리고 변환 함수는 다음과 같습니다 :
export class MyPipe implements PipeTransform {
transform(value:any, args:any[]):any {
var arg1 = args[0];
var arg2 = args[1];
...
}
}
실제 파이프가 없습니다.
{{ myData | date:'fullDate' }}
콜론 (:)으로 여러 매개 변수를 구분할 수 있습니다.
{{ myData | myPipe:'arg1':'arg2':'arg3' }}
또한 파이프를 다음과 같이 연결할 수 있습니다.
{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}
beta.16부터 매개 변수는 transform()
더 이상 메소드에 배열로 전달되지 않고 개별 매개 변수로 전달됩니다 .
{{ myData | date:'fullDate':'arg1':'arg2' }}
export class DatePipe implements PipeTransform {
transform(value:any, arg1:any, arg2:any):any {
...
}
https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26
파이프는 이제 모든 인수를 포함하는 배열이 아닌 가변 개수의 인수를 사용합니다.
Angular 2+의 파이프를 사용하여 객체 배열을 필터링합니다. 다음은 여러 개의 필터 인수를 사용하지만 필요에 따라 하나만 보낼 수 있습니다. 다음은 StackBlitz 예제 입니다. 필터링하려는 키를 찾은 다음 제공 한 값으로 필터링합니다. 실제로 매우 간단합니다. 복잡하지 않다면 StackBlitz Example을 확인하십시오 .
* ngFor 지시문에서 호출되는 파이프는 다음과 같습니다.
<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
Hello {{item.first}} !
</div>
여기 파이프가 있습니다
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
transform(myobjects: Array<object>, args?: Array<object>): any {
if (args && Array.isArray(myobjects)) {
// copy all objects of original array into new array of objects
var returnobjects = myobjects;
// args are the compare oprators provided in the *ngFor directive
args.forEach(function (filterobj) {
let filterkey = Object.keys(filterobj)[0];
let filtervalue = filterobj[filterkey];
myobjects.forEach(function (objectToFilter) {
if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
// object didn't match a filter value so remove it from array via filter
returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
}
})
});
// return new array of objects to *ngFor directive
return returnobjects;
}
}
}
And here is the Component containing the object to filter,
import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
items = [{ title: "mr", first: "john", last: "jones" }
,{ title: "mr", first: "adrian", last: "jacobs" }
,{ title: "mr", first: "lou", last: "jones" }
,{ title: "ms", first: "linda", last: "hamilton" }
];
}
GitHub Example: Fork a working copy of this example here
*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.
Happy Coding :-)
Extended from : user3777549
Multi-value filter on one set of data(reference to title key only)
HTML
<div *ngFor='let item of items | filtermulti: [{title:["mr","ms"]},{first:["john"]}]' >
Hello {{item.first}} !
</div>
filterMultiple
args.forEach(function (filterobj) {
console.log(filterobj)
let filterkey = Object.keys(filterobj)[0];
let filtervalue = filterobj[filterkey];
myobjects.forEach(function (objectToFilter) {
if (!filtervalue.some(x=>x==objectToFilter[filterkey]) && filtervalue != "") {
// object didn't match a filter value so remove it from array via filter
returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
}
})
});
참고URL : https://stackoverflow.com/questions/36816788/how-do-i-call-an-angular-2-pipe-with-multiple-arguments
'IT' 카테고리의 다른 글
MySQL에서 현재 시간에 2 시간을 추가 하시겠습니까? (0) | 2020.06.08 |
---|---|
임대 Blob이 포함 된 Azure 저장소 계정을 어떻게 삭제합니까? (0) | 2020.06.08 |
iOS에서 프로그래밍 방식으로 절전 모드를 비활성화 / 활성화하는 방법은 무엇입니까? (0) | 2020.06.08 |
IncludeExceptionDetailInFaults를 켭니다 (ServiceBehaviorAttribute 또는 (0) | 2020.06.08 |
""를 사용하여 문자열을 초기화하는 방법은 무엇입니까? (0) | 2020.06.08 |