반응형
템플릿의 구조를 변경하는 Structural directive의 하나로 한 요소에 하나의 다른 구조 디렉티브와 사용이 불가능합니다.
사용예시
1. 일반 for 문
<!-- ngfor1.component.html -->
<ul *ngFor="let u of users; let i = index">
<li>ID: {{i}}</li>
<li>First Name: {{ u.firstName }} </li>
<li>Last Name: {{ u.lastName }} </li>
<li>Age: {{ u.age }} </li>
</ul>
// ngfor1.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-ngfor1',
templateUrl: './ngfor1.component.html',
styleUrls: ['./ngfor1.component.css'],
})
export class Ngfor1Component implements OnInit {
users: { firstName: string; lastName: string; age: number }[] = [];
constructor() {
this.users = [
{
firstName: 'top',
lastName: 'floor',
age: 20,
},
{
firstName: 'jack',
lastName: 'bottom',
age: 22,
},
{
firstName: 'what',
lastName: 'the',
age: 11,
},
{
firstName: 'who',
lastName: 'are',
age: 30,
},
{
firstName: 'i',
lastName: 'am',
age: 35,
},
];
}
ngOnInit(): void {}
}
2. 인덱스 사용
<!-- ngfor-with-index.component.html -->
<ul *ngFor="let u of users; let i = index">
<li>ID: {{i}}</li>
<li>First Name: {{ u.firstName }} </li>
<li>Last Name: {{ u.lastName }} </li>
<li>Age: {{ u.age }} </li>
</ul>
// ngfor-with-index.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-ngfor-with-index',
templateUrl: './ngfor-with-index.component.html',
styleUrls: ['./ngfor-with-index.component.css'],
})
export class NgforWithIndexComponent implements OnInit {
users: { firstName: string; lastName: string; age: number }[] = [
{
firstName: 'top',
lastName: 'floor',
age: 20,
},
{
firstName: 'jack',
lastName: 'bottom',
age: 22,
},
{
firstName: 'what',
lastName: 'the',
age: 11,
},
{
firstName: 'who',
lastName: 'are',
age: 30,
},
{
firstName: 'i',
lastName: 'am',
age: 35,
},
];
constructor() {}
ngOnInit(): void {}
}
소스코드
https://github.com/jin-co/web-mobile/tree/master/Angular/cheat-sheet/ngFor
이상으로 구조디렉티브의 하나인 ngFor에 대해서 알아보았습니다.
728x90
반응형
'프론트엔드 > 앵귤러' 카테고리의 다른 글
앵귤러 서비스 (Service) (0) | 2023.01.25 |
---|---|
앵귤러 directives - ngIf (0) | 2023.01.24 |
앵귤러 (Front) - 배포하기 (Vercel) (0) | 2023.01.24 |
앵귤러 (Front) - 배포하기 (Netlify) (0) | 2023.01.22 |
앵귤러 - Observable (0) | 2023.01.19 |