2017-12-29 40 views
2

내가 다음과 같습니다 객체의 배열이 있습니다어떻게하면 개체의 배열을 반복하고 그룹 레이블을 바꿀 수있는 마지막 하나?

[ 
    {group_label: Colors, label: Red, value: '1'}, 
    {group_label: Colors, label: Green, value: '2'}, 
    {group_label: Sizes, label: S, value: '3'}, 
    {group_label: Sizes, label: M, value: '4'}, 
    {group_label: Sizes, label: L, value: '5'} 
] 

을 그리고 난 * ngFor으로 반복하고이 결과를 얻으려면 :

Colors: 
    Red: 1 
    Green: 2 
Sizes: 
    S: 3 
    M: 4 
    L: 5 

을 내 문제가, 내가 어떻게 할 각 "섹션"시작 부분에 한 번만 group_label을 표시하십시오. FormArrays의 Angulars FormGroup이므로이 작업에 더 적합한 개체를 다시 포맷 할 수 없습니다.

답변

1

:

@Pipe({name: 'group'}) 
export class GroupPipe implements PipeTransform { 
    transform(values: Array<any>): Array<any> { 
    // {group_label: Colors, label: Red, value: '1'} 
    const groups = values.reduce((all, row) => { 
     all[row.group_label] = all[row.group_label] || []; 
     all[row.group_label].push(row); 
    }, {}); 
    return Object.keys(groups).map(group => ({ group_label: group, labels: groups[group]})); 
    } 
} 

이제 중첩 사용하십시오 ngFor :

<div *ngFor="let group of (unsortedGroups | group)"> 
    {{ group.group_label }} 
    <div *ngFor="let label of group.labels"> 
    {{ label.label }}: {{ label.value }} 
    </div> 
</div> 
2

두 개의 ngFor를 사용하여 기능별 그룹 또는 사용자 지정 파이프를 만드는 유일한 방법이라고 생각합니다. 그런 다음 두 번째 ngFor를 사용하여 키 값 쌍을 작성할 수 있습니다.

적어도 우아한 방법은 인덱스로 이전 요소를 참조하고 group_label이 다른지 확인하고 그 새로운 섹션을 작성하는 것입니다. 이 경우 이미 배열을 정렬해야합니다!

당신은 그룹이에 파이프를 생성 할 수 있습니다
+0

흠이 "래퍼"로 빌더를 형성하기 위해 다음 formArray을 추가하는 것보다 더 복잡한 것 같다 :) –