각도 키 값 파이프 정렬 속성/순서대로 반복
각도 키 값 파이프를 사용하여 다음과 같이 객체의 특성에 대해 반복하는 경우:
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
속성이 예상된 순서로 반복되지 않는 문제가 발생했습니다.이 코멘트는 이 문제를 경험한 것은 저뿐만이 아님을 시사합니다.
Angular에서 ngFor를 사용하여 객체 속성을 루프 오버하는 방법
키 값 파이프를 사용할 때 반복 순서를 결정하는 것과 특정 반복 순서를 강제하는 방법을 조언해 주시겠습니까?저의 이상적인 반복 순서는 속성이 추가된 순서입니다.
감사해요.
Angular 설명서에 따르면keyvalue합니다.key디폴트로 주문합니다.할 수 .key에 합니다.value또는 오브젝트 속성의 엔트리 순서로 이동합니다.
다음 비교기 함수는 항목을 다양한 순서로 정렬합니다.
// Preserve original property order
originalOrder = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {
return 0;
}
// Order by ascending property value
valueAscOrder = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {
return a.value.localeCompare(b.value);
}
// Order by descending property key
keyDescOrder = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {
return a.key > b.key ? -1 : (b.key > a.key ? 1 : 0);
}
keyvalue 링크:
<div *ngFor="let item of object | keyvalue: originalOrder">
{{item.key}} : {{item.value}}
</div>
<div *ngFor="let item of object | keyvalue: valueAscOrder">
{{item.key}} : {{item.value}}
</div>
<div *ngFor="let item of object | keyvalue: keyDescOrder">
{{item.key}} : {{item.value}}
</div>
데모는 이 스택블리츠를 참조하십시오.
또는 「」의 제공null예: "비교자").originalOrder이 경우 예외가 발생합니다(다음 스택블리츠 참조).
<!-- The following syntaxes preserve the original property order -->
<div *ngFor="let item of object | keyvalue: 0">
<div *ngFor="let item of object | keyvalue: 374">
<div *ngFor="let item of object | keyvalue: null">
<!-- but they cause an exception (visible in the console) -->
ERROR TypeError: The comparison function must be either a function or undefined
또한 템플릿에서 해당 구문을 두 번 사용해도 항목이 전혀 표시되지 않습니다.따라서 추천하지 않습니다.★★★★★★★★★★★★★★★★★★★★★★★★★★★★에 주의해 주세요.undefined 항목은 comparr에 따라 됩니다.츠키다keydiscloss.discloss 。
<div *ngFor="let item of object | keyvalue: 0">
{{item.key}} : {{item.value}}
</div>
직접 쓰면 json과 같은 순서로 데이터를 얻을 수 있습니다.
keyvalue: 0
예, 기본적으로 키 값 쌍은 데이터를 오름차순으로 정렬합니다.
정렬되지 않은 상태로 유지하려면 다음과 같이 수정하십시오.
keyvalue: 0
최종 코드:
<div *ngFor="let item of object | keyvalue:0">
{{item.key}}:{{item.value}}
</div>
그러나 각도 7 이상의 경우 데이터가 정렬되지 않도록 빈 함수를 넣어야 합니다.
<div *ngFor="let item of object | keyvalue: unsorted">
{{item.key}}:{{item.value}}
</div>
고객님의 고객명.ts이데올로기 때문에
unsorted() { }
도움이 됐으면 좋겠네요.
사용할 수 있는 객체 순서를 유지하려면
keepOrder = (a, b) => {
return a;
}
예를 들어 다음과 같이 합시다.
wbs = {
"z": 123,
"y": 456,
"x": 789,
"w": 0#*
}
키 값을 사용하면 키별 알파벳 순서가 지정됩니다.
w 0#*
x 789
y 456
z 123
적용 : keep Order 오브젝트 순서를 유지합니다.
<ion-item *ngFor="let w of wbs | keyvalue: keepOrder">
<ion-label>{{ w.key }}</ion-label>
<ion-label>{{ w.value }}</ion-label>
</ion-item>
이는 승인된 답변과 동일하지만 더 복잡한 객체를 가지고 있기 때문에 사용자 정의 인덱스 필드로 정렬하는 방법과 키밸 파이프를 사용하는 방법에 도움이 될 수 있습니다.
각도 구성 요소:
myObject = {
"key1": { val:"whateverVal1", code:"whateverCode1", index: 1},
"key2": { val:"whateverVal2", code:"whateverCode2", index: 0},
"key3": { val:"whateverVal3", code:"whateverCode3", index: 2}
}
구성 요소의 정렬 기능:
indexOrderAsc = (akv: KeyValue<string, any>, bkv: KeyValue<string, any>): number => {
const a = akv.value.index;
const b = bkv.value.index;
return a > b ? 1 : (b > a ? -1 : 0);
};
템플릿:
<div *ngFor="let x of myObject | keyvalue:indexOrderAsc">
...
</div>
디폴트 덮어쓰기 선호keyvalue내 파이프에 연장해서 행동할 수 있어그러면 나는 내 파이프로필을 사용한다.keyvalue템플릿에 있습니다.
import {Pipe} from '@angular/core';
import {KeyValuePipe} from '@angular/common';
const keepOrder = (a, b) => a;
// This pipe uses the angular keyvalue pipe but doesn't change order.
@Pipe({
name: 'defaultOrderKeyvalue'
})
export class DefaultOrderKeyvaluePipe extends KeyValuePipe {
public transform(value, compareFn = keepOrder) {
return super.transform(value, compareFn);
}
}
다음 코드 조각을 사용해 보십시오.
<div *ngFor="let item of object | keyvalue: 0">
{{item.key}} : {{item.value}}
</div>
네.Object속성들은 랜덤하게 반복됩니다.이것은, 다음과 같이 보존되지 않기 때문입니다.array기억 속에.그러나 속성별로 정렬할 수 있습니다.
삽입 위치로 반복하려면 다음과 같은 추가 속성을 하나 만들어야 합니다.index를 설정합니다.timestamp에 따라 정렬하다index.
아래는 정렬 및 반복을 제어하는 데 사용할 수 있는 파이프입니다.
파이프
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({name: 'values'})
export class ValuesPipe implements PipeTransform {
transform(value: any, args?: any[]): Object[] {
let keyArr: any[] = Object.keys(value),
dataArr = [],
keyName = args[0];
keyArr.forEach((key: any) => {
value[key][keyName] = key;
dataArr.push(value[key])
});
if(args[1]) {
dataArr.sort((a: Object, b: Object): number => {
return a[keyName] > b[keyName] ? 1 : -1;
});
}
return dataArr;
}
}
사용.
<div *ngFor='#item in object | values:"keyName":true'>...</div>
저는 이것이 더 깨끗한 해결책이라고 생각합니다.올바른 주문에 필요한 반품 명세서의 코멘트를 해제합니다.
interface KeyValue<K, V> {
key: K,
value: V
}
// Order by descending property key
keyOrder = (aA: KeyValue<string,any>, bB: KeyValue<string,any>): number => {
const a = aA.value.index;
const b = bB.value.index;
//return a > b ? 1 : (b > a ? -1 : 0); // ASCENDING
return a > b ? -1 : (b > a ? 1 : 0); // DESCENDING
}
사용 사례
<div *ngFor="let x of y | keyvalue: keyOrder;">
{{ x.key }} indexes: {{ x.value.index }}
</div>
기본값을 순서 없음으로 설정하도록 파이프 만들기:
// src/app/pipes/new-key-value.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { KeyValuePipe } from '@angular/common';
import { KeyValueDiffers } from '@angular/core';
const unordered = (a,b)=>0
@Pipe({
name: 'newkeyvalue'
})
// This pipe uses the angular keyvalue pipe. but defaults to unordered.
export class NewKeyValuePipe implements PipeTransform {
constructor(public differs: KeyValueDiffers){};
public transform (value, compareFn = unordered){
let pipe = new KeyValuePipe(this.differs);
return pipe.transform(value, compareFn)
}
}
링크:
파이프에서 Angular2 파이프를 호출할 수 있습니까?
https://github.com/angular/angular/blob/8.2.14/packages/common/src/pipes/keyvalue_pipe.ts#L25-L89
템플릿 사용:
// src/app/some-component/some-component.html
<div *ngFor="let x of myObject | newkeyvalue>
</div>
module.ts에 등록합니다.
// src/app/app.module.ts
import { NewKeyValuePipe } from '@/pipes/new-key-value.pipe.ts'
...
@NgModule({
declarations: [
...
NewKeyValuePipe,
...
]
...
})
Angular 13과 함께.
<div *ngFor="let item of object | keyvalue: 0">
{{item.key}} : {{item.value}}
</div>
keyvalu: 0
는 동작하고 있지 않지만, 기존의 어레이 오브젝트에 대해서 어떠한 조작도 실행하지 않는 경우는, 빈 정렬되지 않은 메서드가 동작하고 있습니다.
<div *ngFor="let item of object | keyvalue: unsorted">
{{item.key}}:{{item.value}}
</div>
.ts 파일에 이 함수를 입력합니다.
unsorted() { }
언급URL : https://stackoverflow.com/questions/52793944/angular-keyvalue-pipe-sort-properties-iterate-in-order
'programing' 카테고리의 다른 글
| Wordpress - 메뉴 항목에 하위 항목이 있는지 어떻게 알 수 있습니까? (0) | 2023.03.06 |
|---|---|
| Angular.noop은 무엇에 사용됩니까? (0) | 2023.03.06 |
| 기능 상태 비저장 구성 요소의 PropTypes (0) | 2023.03.06 |
| React 구성 요소가 기본 내보내기로 없으면 React/Next 프로젝트 검색 페이지를 빌드할 수 없습니다(콘텍스트 api 파일). (0) | 2023.03.06 |
| 오류: ENOENT: 해당 파일 또는 디렉터리가 없습니다. 오류(네이티브)에서 '/public/main.html'을 stat합니다. (0) | 2023.03.06 |