728x90

JavaScript와 HTML, CSS등에 대해서는 일체 다루지 않는다.

기초지식은 다른 강의를 참조하도록 하라.

또한 Angular에서는 JavaScript로 번역되는 TypeScirpt라는 새로운 언어를 사용한다.

이 언어는 JavaScript에 Type을 추가한 언어로 좀더 객체지향적인 설계가 가능한 언어이다.

이 언어에 대해서 조금씩의 설명은 있겠지만 자세한 설명은 다루지 않을 계획이다.

필자는 아직 이 TypeScript를 강의로 제공할 생각이 없으므로 자세히 알고싶다면

https://www.typescriptlang.org/

를 참조하라.


angular에서  for문을 사용하는 예제를 한번 보도록하자.

angular에서 for문의 대상은 아래와 같다.


1. array순회

2. object순회

3. class순회

4. range순회(일반적인 for문)


array순회


import {Component} from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
nameList = ['kukaro', 'jiharu', 'limzz', 'ekekdid'];
}


위와 같이 nameList를 넘겼다고 가정해보자.

이 리스트를 for문으로 순회하는 코드를 보자


<ul *ngFor="let name of nameList">
<li>{{name}}</li>
</ul>


for문을 쓸때는 *ngFor이라는 키워드를 사용해야한다.

여기서 안의 코드를 보면 let name of nameList라는 구문이 있다.

이는 TypeScript의 코드의 for문 구문이다.


for (let name of this.nameList) {
console.log(name);
}

TypeScript에서 for문 구문을 사용할 때 위와 같은 형태로 사용한다.

let이라는 것은 TypeScript에서 일반 변수 선언을 의미한다.

즉 자바스크립트에서 var의 역활이라고 생각해도 된다.

TypeScript에서 for문의 이터레이블을 순회할때 사용하는것은 of이다.

이는 다른 언어에서 in을 사용하는 것과는 대조적이다.

위의 코드로 array를 순회할 수 있다.


object순회


TypeScript에서 말하는 object는 class를 의미하는게 아니라 자바스크립트의 연관배열, 즉 딕셔너리를 의미한다.


import {Component} from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
nameList = {'kukaro': '26', 'jiharu': '26', 'limzz': '24', 'ekekdid': '25'};
objectKeys = Object.keys;
}


object는 순회하기위해서는 key를 저장해서 같이 넘겨줘야한다.

받는 쪽에서 사용하는 방식도 array와는 다르다.


<ul *ngFor="let key of objectKeys(nameList)">
<li>{{key}} : {{nameList[key]}}</li>
</ul>


이제 둘다 값이 넘어같고 이터레이터는 Object.keys 변수로 순회해 줘야한다.

보면 어떻게 사용해야할지 쉽게 감이 올 수 있다.

약간 불편한 방식이지만... 놀랍게도 이 방법밖에 없다.

잘 외워둘 필요가 있다.


class순회


//animal.ts
export class Animal {
private _name: string;
private _foot: number;

constructor(name: string, foot: number) {
this._name = name;
this._foot = foot;
}

get name(): string {
return this._name;
}

set name(value: string) {
this._name = value;
}

get foot(): number {
return this._foot;
}

set foot(value: number) {
this._foot = value;
}
}


이는 animal.ts로 Animal클래스를 보도록 하자.

사실 크게 볼건 없다. kotlin과 문법이 매우매우매우 흡사하다.

그러나 자바라고 생각하고 접근해도 무방하다.

constructor는 생성자를 의미한다. TypeScript는 변수를 뒤에 선언해준다.

또한 private변수에는 _(언더스코어)를 붙혀주는게 관례이다.

이는 JavaScript시절부터 내려오는 관례이다.

get과 set은 게터와 세터이며 이는 자바에는 없는 문법이지만

python이나 kotlin,C#에 등장하는 문법이다. 우리가 아는 게터와 세터와 같다.

외부에서 사용하기 위해서 export키워드를 선언해 준다.


import {Component} from '@angular/core';
import {Animal} from './animal';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
animalList = [new Animal('elephant', 4),
new Animal('kukaro', 2,
)];
}


위 코드에서는 Animal클래스를 임포트해서 사용하고 있다.

그리고 배열을 만들어서 Animal객체를 두개 생성해서 넘겨보았다.

받을때는 아래와 같이 받는다.


<ul *ngFor="let animal of animalList">
<li>{{animal.name}}:{{animal.foot}}</li>
</ul>


일반적으로 객체에서 대려와서 사용하듯이 사용하면된다.



range순회


range순회는 일반적인 방식이지만 생각보다 사용하기 어렵다.

둘다 꼼수에 가까운 방식이므로 뭐가 정석이라고 말하기는 힘들다.

여러분이 사용하기 편한 방식으로 사용하면되겠다.


import {Component} from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
numbers = Array.from(Array(10).keys());
}


보다시피 배열을 넘겨 주면 된다. Array(10)은 10칸차리 배열이 생성된다.

keys()를 호출하면 배열의 키값이 호출되므로 그 값은 0부터 9까지가 된다.

Array.from은 다른 배열로 부터 배열을 만드는 메소드이다.

따라서 위의 결과로 numbers라는 배열은 0부터 9가 적재된 배열이다.

이제 그냥 배열 처럼 호출하면된다.


<ul *ngFor="let number of numbers">
<li>{{number}}</li>
</ul>

위와같은 형식으로 호출하면 된다는 것이다.

이 방식은 html단에서는 직관적이고 깨끗해지고 typescript단에서는 조금 지저분해진다는 단점이 있다.

사실 단점이라고 보기는 힘들어서 이 방식이 대중화 되있긴 하다.


이제 두번째 방식을 보자.


import {Component} from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
arr = new Array(10);
}


두번째로는 그냥 배열을 선언해주는것이다.

위처럼 선언하면 초기화가 되있지 않다.

이제 받는 부분을 보자.


<ul *ngFor="let atom of arr; let i=index">
<li>{{i}}</li>
</ul>

html단에서 코드가 다른데 일단 for문을 호출한느데 연달아서 index라는 예약된 지시어를 호출해준다.

이 지시어는 for문을 순회할때 0부터 순서대로 적재된다.

위의 구문역시 for문을 사용한 구문이 된다는 것이다.

이 방식은 ts단에서는 깔끔해지나 html에서 더러워진다.

다만 보통의 경우 범위만 넘겨서 프론트에서 표시되는 경우는 드물기 때문에

객체를 함께 넘겨왔을때 사용하는 이방식도 많이 사용된다.

둘 중 본인이 편한, 상황에 맞는 방식을 사용하는 것이 중요하다.


+ Recent posts