[Angular] Record / keyvalue pipe

Dorong·2023년 12월 12일
0

Angular

목록 보기
8/9
post-thumbnail

✅ Record

  • TypeScript에서 사용되는 유형 표기
  • Record<K, T>는 K 타입의 키와 T 타입의 값을 갖는 객체
  eventsInIndexWeek = computed<Record<string, testDTO[]>>(() => {
    const result: Record<string, testDTO[]> = {};
    for (let i = 0; i < 7; i++) {
      const index = this.indexDate().add(i, 'day');
      const filtered = this.eventInformations()?.filter((eventInformation) =>
        index.isSame(eventInformation.startAt, 'date')
      );

      result[index.format('YYYY-MM-DD')] = filtered;
    }

    return Object.keys(result)
      .sort((a, b) => (dayjs(a).isBefore(b) ? 1 : -1))
      .reduce<Record<string, testDTO[]>>((obj, key) => {
        obj[key] = result[key];
        return obj;
      }, {});
  });

✅ keyvalue pipe

  • 객체나 Map과 같이 key-value 쌍을 포함하는 데이터 구조를 배열로 변환
// 이런 코드가 있다면
{
  first: 'Value 1',
  second: 'Value 2'
}

// keyvalue pipe를 사용하면
[
  { key: 'first', value: 'Value 1' },
  { key: 'second', value: 'Value 2' }
]

// 사용은 이렇게
<div *ngFor="let item of objectItems | keyvalue">
  {{ item.key }}: {{ item.value }}
</div>

// angular17에서는 이렇게
@For(let item of objectItems | keyvalue){
	<div>{{ item.key }}: {{ item.value }}</div>
}
profile
🥳믓진 개발자가 되겠어요🥳

0개의 댓글