재정렬할 수 있는 몇 가지 항목이 있는 작은 목록이 있습니다( stackblitz 참조 ). 내부적으로 해당 목록은 지도로 구현됩니다. 편리하게도 Angular는 파이프 키값을 제공하므로 다음과 같이 맵을 쉽게 반복할 수 있습니다.
*ngFor="let item of doc.items | keyvalue:sortHash"
목록 정렬을 처리할 함수 sortHash를 제공할 수 있습니다. cdkDropList
목록에 DnD 순서를 제공하기 위해 사용하고 싶습니다 . 배열을 사용할 때 이것은 간단합니다.
(cdkDropListDropped)="dropItem($event, doc.items, doc)
cdkDropListDropped
배열 내에서 항목 이동을 처리 하는 함수를 전달하기 만 하면 됩니다. Angular는 다음과 같은 내장 함수 moveItemInArray
를 제공합니다.
import { moveItemInArray } from '@angular/cdk/drag-drop';
...
async dropItem(event: CdkDragDrop<string[]>, list: any, doc: any) {
moveItemInArray(list, event.previousIndex, event.currentIndex);
}
이것은 배열에서 예상대로 작동하지만 제 경우에는 "order" 속성으로 순서가 정의된 맵에 의존합니다. 내 데이터 구조를 참조하십시오.
doc = {
meta: {
text: 'title',
...
},
items: {
SEC_000000: {
meta: {
text: 'Episode I - The Phantom Menace',
order: '0',
...
},
},
SEC_111111: {
meta: {
text: 'Episode II - Attack of the Clones',
order: '1',
...
},
},
SEC_222222: {
meta: {
text: 'Episode III - Revenge of the Sith',
order: '2',
...
},
},
},
};
따라서 내 dropItem
기능은 약간 다릅니다.
doc.items
)를 배열로 변환합니다.moveItemInArray
함수를 사용하여 배열 내부의 항목을 효과적으로 이동합니다.정렬 기능은 예상대로 작동하지만 DnD 시 UI가 업데이트되지 않습니다.
다음은 단순화된 샘플 코드 가 있는 stackblitz 입니다. 내가 여기서 무엇을 놓치고 있습니까?
답은 Angular 코어 깊숙이 있습니다. 를 사용하고 KeyValuePipe
있습니다. 출처 여기 .
우리가 관심을 갖는 파이프 부분은 다음과 같습니다.
const differChanges: KeyValueChanges<K, V>|null = this.differ.diff(input as any);
const compareFnChanged = compareFn !== this.compareFn;
if (differChanges || compareFnChanged) {
this.keyValues.sort(compareFn);
this.compareFn = compareFn;
}
차이가 입력 개체에서 차이를 찾으면 정렬 기능이 실행됩니다.
로그를 콘솔 에 표시 하고 보기가 초기화된 후 differChanges
일관되게 반환되는 것을 확인할 수 있습니다. null
왜요? 다른 코드 를 살펴봐야 합니다 .
// Add the record or a given key to the list of changes only when the value has actually changed
private _maybeAddToChanges(record: KeyValueChangeRecord_<K, V>, newValue: any): void {
if (!Object.is(newValue, record.currentValue)) {
record.previousValue = record.currentValue;
record.currentValue = newValue;
this._addToChanges(record);
}
}
차이점은 Object.is(newValue, record.currentValue)
값이 변경되었는지 확인하는 데 사용됩니다. 이 경우 diff할 객체의 값은 객체 자체이며 Object.is()
깊은 동등성을 평가하지 않습니다.
따라서 최소한 두 가지 옵션이 있습니다.
사용자 지정 무차별 대입 전략 keyvalue
파이프 를 사용 하여 작동하는 StackBlitz를 만들었습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다