본문 바로가기

프로그래밍/AngularJs

AngularJs 2 - display data

이전에 작성했던 허전한 화면을 조금 채워 보자.


angularjs 관련 코드를 보여주는 리스트를 만들기로한다.


우선, 보여줄 코드에 대한 정의를 code.example.ts라는 파일로 만든다. 우선 제목과 내용에 해당하는 title, content라는 필드만으로 정의한다.



code.example.ts
export interface CodeExample {
title:string;
content:string;
}
view raw code.example.ts hosted with ❤ by GitHub



위 interface를 사용하여 실제 보여줄 내용을 담은 리스트 클래스를 examples라는 새로운 디렉토리 밑에 작성한다.



mock-example-codes.ts
import {CodeExample} from '../code.example'
export var ExampleCodes : CodeExample[] = [
{
"title":"main.ts",
"content":`
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app.component'
bootstrap(AppComponent);`
}
];



이렇게 만들어진 내용을 어디에 보여줄 것인가? 우선은 별 내용도 없는 페이지인 app.component.html에 보여주자.



<h1>{{title}}</h1>
<ul *ngIf="codes.length">
<li *ngFor="#code of codes">{{code.title}} = {{code.content}}</li>
</ul>



바뀐 코드는 위와 같고, 2번째 줄에서 *ngIf, *ngFor라는 지시자를 사용했는데 이는 다른 언어들의 if 와 for 에 해당한다. 그럼 여기서 치환되어여할 {{code.title}}, {{code.content}}는 어디서 와야할까? 물론 방금 전에 만든 mock-example-codes.ts에 있는 Codes라는 배열값들이 들어가도록 할 것이다. 그러려면 app.component.html에 데이터를 전달해주는 app.component.ts파일에 code라는 필드를 정의해야 한다.



import {Component} from 'angular2/core';
import {ExampleCodes} from './examples/mock-example-codes';
@Component({
selector: 'my-app',
templateUrl: 'app/html/app.component.html'
})
export class AppComponent {
title = 'AngularJs 2 Example Code Library';
codes = ExampleCodes;
}


이제 화면을 다시 띄워 보면 main.ts = ...라는 리스트 한줄이 추가 되어있다.