Old/old-Angularjs2

2. AngularJS 2.0 튜토리얼 따라하기

양디 2016. 1. 10. 20:47

그림 클릭시 정식 홈페이지로 이동합니다.



개발 환경 구성


먼저 시작하기에 앞서 알아두어야 할 점은, AngularJS는 2.0 버전부터 Microsoft에서 개발하는 Javascript의 superset 언어인 Typescript를 기본으로 제작되고 있습니다.


따라서 2.0을 실행하기 위해선 Typescript Compiler를 통하여 javascript로 바꾸어야 인터넷 브라우저가 정상적으로 읽어줄 수 있습니다.


그러한 모듈들을 모두 설치하여야 합니다.


먼저 npm으로 모듈들을 다운로드하기 위하여 package.json 파일을 수정하여야 합니다.



package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
  "name""express",
  "version""0.0.0",
  "private"true,
  "scripts": {
    "tsc""tsc",
    "tsc:w""tsc -w",
    "start""concurrent \"npm run tsc:w\" \"npm run express\" ",
    "express""node ./bin/www"
  },
  "dependencies": {
    "body-parser""~1.13.2",
    "cookie-parser""~1.3.5",
    "debug""~2.2.0",
    "ejs""~2.3.3",
    "express""~4.13.1",
    "morgan""~1.6.1",
    "node-sass-middleware""0.8.0",
    "serve-favicon""~2.3.0",
    "socket.io""^1.4.3",
    "angular2""2.0.0-beta.0",
    "systemjs""0.19.6",
    "es6-promise""^3.0.2",
    "es6-shim""^0.33.3",
    "reflect-metadata""0.1.2",
    "rxjs""5.0.0-beta.0",
    "zone.js""0.5.10"
  },
  "devDependencies": {
    "concurrently""^1.0.0",
    "lite-server""^1.3.1",
    "typescript""^1.7.3"
  }
}
 
cs


위의 내용에서, 초록색으로 표시한 부분이 기존의 express 기본 모듈에서 추가로 집어넣은 부분입니다.


초록색 부분을 추가하여 주시고, 또 Typescript compile을 위한 설정 또한 설정해주어야합니다.


이를 위해 tsconfig.json 파일을 새로 폴더에 만들어줍니다.



tsconfig.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "compilerOptions": {
    "target""ES5",
    "module""system",
    "moduleResolution""node",
    "sourceMap"true,
    "emitDecoratorMetadata"true,
    "experimentalDecorators"true,
    "removeComments"false,
    "noImplicitAny"false
  },
  "exclude": [
    "node_modules"
  ]
}
cs


위의 파일을 만들어서 저장하면 Angularjs 2.0을 사용할 기본 환경은 준비가 되었습니다.


Angular2.ejs 뷰를 위한 설정


저희는 angular2.ejs 라는 파일로 튜토리얼을 진행할 예정입니다.

그런데 express의 옵션을 그대로 사용하면, 바로 띄우지 못합니다. 

angular 2 의 ts파일이 node_modules 폴더 속에 숨어있기 때문인데요, 이를 위해 express 서버에게 node_modules 폴더를 사용하게끔 해주어야 합니다.





1
2
3
./app.js 파일

app.use(express.static(path.join(__dirname, 'public')));
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));
 
cs


express 설정 파일인 app.js 파일에서 2번 라인을 추가해줍니다. 이는 express 서버가 /node_modules 라는 주소를 입력받았을 때에 현재 폴더(__dirname) 안에 있는 node_modules 로 접근하게 만들어라 ! 라는 코드입니다.


또한 라우팅도 설정해주어야겠지요 ?




1
2
3
./routes/index.js 파일

router.get('/angular2'function(req, res, next) {
  res.render('angular2');
});
cs


라우터 파일인 index.js 파일 내부에 위의 내용을 추가해줍니다.

클라이언트가 /angular2 라는 주소로 접근하면 views 폴더에 있는 angular2.ejs 파일을 렌더해서 보내주겠다는 코드입니다.


그럼 express에서 설정은 다 끝났습니다.


뷰를 보여줄 파일인 angular2.ejs 파일을 views 폴더에 만듭니다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
./views/Angular2.ejs 파일

<html>
 
  <head>
    <title>Dalkom Angularjs 2</title>
 
    <!-- 1. Load libraries -->
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
 
    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/boot')
            .then(nullconsole.error.bind(console));
   </script>
 
  </head>
 
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
 
</html>
 
cs


위의 코드를 그대로 복사해서 붙여넣으시면 됩니다.


systemJS 라는 자바스크립트 모듈을 사용해서 app/boot.js 파일을 실행시키는 웹페이지입니다.


아래 디스플레이를 담당할 body부분을 보면, my-app이라는 태그 안에 Loading... 이라는 내용이 있습니다.


이것이 systemjs가 내용을 읽어와서 적용시키기 전에 잠시 보일 글이고, my-app 안에 내용이 들어갈 예정입니다.


./public/app/boot.ts


html 파일에서 불려서 다른 내용들을 전부 가져올 boot.ts 파일을 작성합니다.


위의 html파일에서 위치를 app/boot로 하였으므로, app/boot.ts 파일을 작성합시다.


다른곳에서 불러와야하는 정보이기 때문에, /public 폴더에 집어 넣는 것이 좋습니다.


그 외의 방법을 사용하실거면 express 설정을 손보시면 됩니다.




1
2
3
4
./public/app/boot.ts 파일


import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
 
bootstrap(AppComponent);
cs


내용은 간단합니다.

위의 내용을 집어넣어주시고, 작업은 같은 app 폴더 내부에 app.component.ts 파일에서 할 예정입니다.


./public/app/app.component.ts

실제로 출력될 내용을 관리하는 app.component.ts 파일입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import {Component} from 'angular2/core';
 
interface Person {
  id: number;
  name: string;
  webpage: string;
}
 
@Component({
  selector: 'my-app',
  template:`
    <h1>{{title}}</h1>
    <h2>I'm {{person.name}}!</h2>
    <div>My Website : <a href={{person.webpage}}>{{person.webpage}}</a></div>
    <div>
      <label>name: </label>
      <div><input [(ngModel)]="person.name" placeholder="name"></div><br>
      <label>webpage: </label>
      <div><input [(ngModel)]="person.webpage" placeholder="webpage"></div>
    </div>
    `
})
export class AppComponent {
  public title = 'Dalkom IT World';
  public person: Person = {
    id: 1,
    name: 'YangD',
    webpage:'http://www.dalkomit.com'
  };
}
 
cs

위와같이 입력하시면 됩니다.


먼저 angular2 의 주요 옵션들을 사용하기 위해 angular2/core를 임포트합니다.


임의로 튜토리얼을 위한 Person interface를 만들었습니다. id, name, webpage를 저장하게 만들었습니다.


component에는 angular2 의 주요한 여러 부분들을 설정할 수 있습니다.

selector 에는 my-app이라고 하였는데, 이는 angular를 부르는 웹페이지에서 내용이 들어갈 태그가 되겠습니다.


template은 selector에 들어갈 내용들이 들어가게 됩니다.


보면 angular 의 특별한 기능인 {{변수}} 가 보입니다. 여기에서는 {{person.name}} 등으로 쓰였네요.

현재 페이지에서 해당하는 값이 변하면 바로 값을 적용시켜줍니다.


또 input 태그에서는 [(ngModel)] 라는 속성값이 보이네요. 이 속성을 통해서 이 input이 person.name 값을 변경시키도록 적용시킬 수 있습니다.


마지막으로 아래 class AppComponent에서 내용을 적용하게 되는데, title은 Dalkom IT World로,

사용될 객체인 person은 Person 인터페이스를 가지고 있으며, 내용은 아래와 같습니다.


이렇게 저장해서 실행하면 다음과 같은 웹페이지가 나옵니다.







위의 YangD로 들어가 있는 input을 바꾸면 위의 I'm 부분이 바뀌고,

webpage를 바꾸면 아래 My Website 부분이 바뀝니다. 클릭하면 실제로 적용되는 것을 알 수 있습니다.


아주 기초적인 내용이지만, 처음이라면 직접 실습해보시면 도움이 될겁니다 !




Point !

Angular2.0은 typescript로 짠다.

{{변수}}와 [(ngModel)] 속성값을 기억하자.





댓글