각도 2 정렬 및 필터
Angularjs 1에서는 다음과 같은 방식으로 정렬하고 필터링 할 수 있습니다.
<ul ng-repeat="friend in friends | filter:query | orderBy: 'name' ">
<li>{{friend.name}}</li>
</ul>
그러나 Angularjs 2.0에서이를 수행하는 방법에 대한 예를 찾을 수 없습니다. 내 질문은 Angularjs 2.0에서 정렬 및 필터링하는 방법입니다. 여전히 지원되지 않는 경우 Angularjs 2.0에 언제 또는 언제 포함 될지 아는 사람이 있습니까?
Angular 팀은 Angular 2가 최소화되기를 원하기 때문에 즉시 추가되지 않습니다. OrderBy는 축소와 함께 깨지는 반사를 실행합니다. 문제에 대한 Miško Heverey의 답변 을 확인하십시오 .
단일 및 다차원 배열을 모두 지원하는 OrderBy 파이프를 만드는 데 시간이 걸렸습니다. 또한 다차원 배열의 여러 열에서 정렬 할 수 있도록 지원합니다.
<li *ngFor="let person of people | orderBy : ['-lastName', 'age']">{{person.firstName}} {{person.lastName}}, {{person.age}}</li>
이 파이프를 사용하면 페이지를 렌더링 한 후 배열에 더 많은 항목을 추가 할 수 있으며 새 항목으로 배열을 올바르게 정렬 할 수 있습니다.
그리고 여기에 작동하는 데모가 있습니다 : http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby 및 https://plnkr.co/edit/DHLVc0?p=info
편집 : http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby에 새 데모 추가
편집 2 : ngFor를 새 구문으로 업데이트했습니다.
다음은 문자열 값 (ES6)이있는 속성을 포함하는 객체 배열에 대한 간단한 필터 파이프입니다.
filter-array-pipe.js
import {Pipe} from 'angular2/core';
// # Filter Array of Objects
@Pipe({ name: 'filter' })
export class FilterArrayPipe {
transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}
}
구성 요소
myobjComponent.js
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {FilterArrayPipe} from 'filter-array-pipe';
@Component({
templateUrl: 'myobj.list.html',
providers: [HTTP_PROVIDERS],
pipes: [FilterArrayPipe]
})
export class MyObjList {
static get parameters() {
return [[Http]];
}
constructor(_http) {
_http.get('/api/myobj')
.map(res => res.json())
.subscribe(
data => this.myobjs = data,
err => this.logError(err))
);
}
resetQuery(){
this.query = '';
}
}
템플릿에서
myobj.list.html
<input type="text" [(ngModel)]="query" placeholder="... filter" >
<div (click)="resetQuery()"> <span class="icon-cross"></span> </div>
</div>
<ul><li *ngFor="#myobj of myobjs| filter:query">...<li></ul>
설계 상 지원되지 않습니다. sortBy 파이프는 프로덕션 규모 앱에 실제 성능 문제를 일으킬 수 있습니다. 이것은 앵귤러 버전 1의 문제였습니다.
사용자 지정 정렬 기능을 생성해서는 안됩니다. 대신 typescript 파일에서 배열을 먼저 정렬 한 다음 표시해야합니다. 예를 들어 드롭 다운을 선택할 때 순서를 업데이트해야하는 경우이 드롭 다운 선택이 함수를 트리거하고 그에서 호출되는 정렬 함수를 호출하도록합니다. 이 정렬 기능은 다시 사용할 수 있도록 서비스로 추출 할 수 있습니다. 이렇게하면 정렬이 필요할 때만 적용되고 앱 성능이 훨씬 좋아집니다.
파이프는 데이터를 입력으로 받아 원하는 출력으로 변환합니다. 이 파이프 파일을 추가하십시오 : 폴더 orderby.ts안에 /app.
//The pipe class implements the PipeTransform interface's transform method that accepts an input value and an optional array of parameters and returns the transformed value.
import { Pipe,PipeTransform } from "angular2/core";
//We tell Angular that this is a pipe by applying the @Pipe decorator which we import from the core Angular library.
@Pipe({
//The @Pipe decorator takes an object with a name property whose value is the pipe name that we'll use within a template expression. It must be a valid JavaScript identifier. Our pipe's name is orderby.
name: "orderby"
})
export class OrderByPipe implements PipeTransform {
transform(array:Array<any>, args?) {
// Check if array exists, in this case array contains articles and args is an array that has 1 element : !id
if(array) {
// get the first element
let orderByValue = args[0]
let byVal = 1
// check if exclamation point
if(orderByValue.charAt(0) == "!") {
// reverse the array
byVal = -1
orderByValue = orderByValue.substring(1)
}
console.log("byVal",byVal);
console.log("orderByValue",orderByValue);
array.sort((a: any, b: any) => {
if(a[orderByValue] < b[orderByValue]) {
return -1*byVal;
} else if (a[orderByValue] > b[orderByValue]) {
return 1*byVal;
} else {
return 0;
}
});
return array;
}
//
}
}
구성 요소 파일 (app.component.ts)에서 방금 추가 한 파이프를 다음을 사용하여 가져옵니다. import {OrderByPipe} from './orderby';
그런 다음 *ngFor="#article of articles | orderby:'id'"ID별로 오름차순 또는 orderby:'!id'"내림차순 으로 기사를 정렬하려면 템플릿 내부 에 추가 하십시오 .
파이프 이름 뒤에 콜론 (:)과 매개 변수 값을 추가하여 매개 변수를 파이프에 추가합니다.
@Component 데코레이터의 파이프 배열에 파이프를 나열해야합니다. pipes: [ OrderByPipe ].
import {Component, OnInit} from 'angular2/core';
import {OrderByPipe} from './orderby';
@Component({
selector: 'my-app',
template: `
<h2>orderby-pipe by N2B</h2>
<p *ngFor="#article of articles | orderby:'id'">
Article title : {{article.title}}
</p>
`,
pipes: [ OrderByPipe ]
})
export class AppComponent{
articles:Array<any>
ngOnInit(){
this.articles = [
{
id: 1,
title: "title1"
},{
id: 2,
title: "title2",
}]
}
}
내 github 및 내 웹 사이트 의이 게시물에 대한 자세한 정보
배열 정렬을 위해 고유 한 파이프를 만들어야합니다. 여기에이를 수행 할 수있는 한 가지 예가 있습니다.
<li *ngFor="#item of array | arraySort:'-date'">{{item.name}} {{item.date | date:'medium' }}</li>
https://plnkr.co/edit/DU6pxr?p=preview
이것은 내 종류입니다. 숫자 정렬, 문자열 정렬 및 날짜 정렬을 수행합니다.
import { Pipe , PipeTransform } from "@angular/core";
@Pipe({
name: 'sortPipe'
})
export class SortPipe implements PipeTransform {
transform(array: Array<string>, key: string): Array<string> {
console.log("Entered in pipe******* "+ key);
if(key === undefined || key == '' ){
return array;
}
var arr = key.split("-");
var keyString = arr[0]; // string or column name to sort(name or age or date)
var sortOrder = arr[1]; // asc or desc order
var byVal = 1;
array.sort((a: any, b: any) => {
if(keyString === 'date' ){
let left = Number(new Date(a[keyString]));
let right = Number(new Date(b[keyString]));
return (sortOrder === "asc") ? right - left : left - right;
}
else if(keyString === 'name'){
if(a[keyString] < b[keyString]) {
return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
} else if (a[keyString] > b[keyString]) {
return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
} else {
return 0;
}
}
else if(keyString === 'age'){
return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
}
});
return array;
}
}
참고 URL : https://stackoverflow.com/questions/32882013/angular-2-sort-and-filter
'IT TIP' 카테고리의 다른 글
| UITextView의 NSAttributedString에 글꼴을 설정하면 줄 간격이 무시됩니다. (0) | 2020.10.26 |
|---|---|
| 테두리의 두께를 백분율로 설정하는 방법은 무엇입니까? (0) | 2020.10.26 |
| 복사 또는 rsync 명령 (0) | 2020.10.26 |
| C를 사용하여 JSON 구문 분석 (0) | 2020.10.26 |
| Android에서 호스트 파일을 변경하는 방법 (0) | 2020.10.26 |