각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는 최소화와 함께 깨지는 반사가 중단됩니다.이 문제에 대한 미슈코 헤베레이의 답변을 확인해 보세요.
시간을 들여 단일 및 다차원 배열을 모두 지원하는 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/order by에 새 데모 추가
편집 2: ngFor를 새 구문으로 업데이트했습니다.
설계상 지원되지 않습니다.sortBy 파이프는 프로덕션 스케일 앱의 실제 성능 문제를 야기할 수 있습니다.이것은 각진 버전 1의 문제였습니다.
사용자 지정 정렬 함수를 만들지 마십시오.대신, 타이프스크립트 파일에서 배열을 먼저 정렬한 다음 표시해야 합니다.예를 들어 드롭다운을 선택했을 때 순서를 업데이트해야 하는 경우 이 드롭다운 선택을 통해 함수를 트리거하고 정렬 함수를 호출합니다.이 정렬 기능을 다시 사용할 수 있도록 서비스로 추출할 수 있습니다.이렇게 하면 정렬이 필요할 때만 적용되고 앱 성능이 훨씬 향상됩니다.
문자열 값(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>
파이프는 데이터를 입력으로 받아 원하는 출력으로 변환합니다.파이프 파일 추가: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;
}
//
}
}
파일에서 방금 위해 다음과 같이합니다.import {OrderByPipe} from './orderby';
그다음에 추가합니다.*ngFor="#article of articles | orderby:'id'"
만약 당신이 당신의 기사들을 id로 오름차순으로 정렬하기를 원한다면 당신의 템플릿 안에.orderby:'!id'"
내림차순으로
파이프에 매개변수를 추가하는 방법은 파이프 이름에 콜론( : )을 사용한 다음 매개변수 값을 사용하여 추가합니다.
@Component decorator의 파이프 배열에 파이프를 나열해야 합니다.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",
}]
}
}
여기 내 깃허브에 대한 더 많은 정보와 내 웹사이트에 있는 이 게시물
배열 정렬을 위해 자신만의 파이프를 만들어야 하는데, 다음은 어떻게 할 수 있는지 한 가지 예입니다.
<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
'programing' 카테고리의 다른 글
WooCommerce - 랜덤 상품 보여주기 (0) | 2023.09.19 |
---|---|
음의 부호와 가변 길이 숫자를 고려하기 위해 인쇄 f를 어떻게 패드에 넣습니까? (0) | 2023.09.14 |
HTML5로 iPad에서 오디오 파일 자동 재생 (0) | 2023.09.14 |
워드프레스의 위젯 블록 편집기를 비활성화하는 방법? (0) | 2023.09.14 |
PowerShell을 사용하여 처리를 중지합니다. 우회 확인할 수 있습니까? (0) | 2023.09.14 |