Sanghyuk's Dev



안녕하세요.

이번 챕터부터는 Angular 홈페이지 에 있는 Tutorial - The Hero Editor 를 따라하면서 Angular를 배워보겠습니다.

글에 부족한 점이 있다면 위 링크를 타고 가셔서 자세한 정보를 보시기 바랍니다.


가장 먼저 메인페이지에 새로운 글을 삽입해 보겠습니다.

src/app/app.component.html 파일을 아래와 같이 수정합니다.


<h1>{{title}}</h1>

<h2>{{hero}}</h2>


그리고 Title 과 Hero 의 표시 문자를 변경하기 위해 /src/app/app.component.ts 파일을 엽니다.

title 과 hero 변수를 만들고 값을 넣어 줍시다.


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


@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})


export class AppComponent {

  title = 'Tour of Heroes';

  hero = 'Windstorm';

}


이제 제대로 바인딩 되었는지 cmd 에서 서버를 가동시켜 화면을 확인해봅시다.


ng serve




{{title}} 과 {{hero}} 가 제대로 바인딩 되는 것을 확인할 수 있습니다.

여기서 {{ }} 이중 괄호는 단방향 데이터 바인딩을 실행합니다.


이제 영웅을 체계적으로 관리하기 위해 영웅들을 나타내는 Model을 만들어 보겠습니다.

src/app/app.component.ts 파일에 Hero Model class 인 Hero 를 추가합니다.


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


@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})


export class Hero {

  id : number;

  name : string;

}


export class AppComponent {

  title = 'Tour of Heroes';

  hero = 'Windstorm';

}


사실 모델은 전용 파일을 만들어 관리해야 합니다.

하지만 여기서는 튜토리얼을 따라서 진행하도록 하겠습니다.


id : number , name : string 은 TypeScript의 기능 중 하나입니다.

변수이름 : Type 으로 지정하여 해당 변수의 Type 을 지정하는 형식입니다.

기존 Java 나 C# 을 배운 사람들은 익숙하실 겁니다.

이젠 Javascript에서도 Type을 지정하여 더욱 짜임새있는 코드를 짤 수 있습니다.

Class 의 경우 역시 기존 Java, C# 의 Class 와 같은 기능으로 extends 로 상속도 가능하며

interface class, abstract class 도 사용이 가능합니다.


이제 Hero 라는 Class 를 이용하여 기존 영웅을 나타내 보겠습니다.

/src/app/app.component.ts 파일을 열어 첫 번째 히어로를 등록하겠습니다.


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


export class Hero {

  id : number;

  name : string;

}


@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})


export class AppComponent {

  title = 'Tour of Heroes';

  hero : Hero = {

    id : 1,

    name : 'windstorm'

  };

}


여기서 주의해야 할 점이 있습니다.

한 컴포넌트에서 여러 Class를 넣을 때 

@Component 아래에 있는 클래스가 주요 로직 클래스가 되어야 합니다.

아래 코드처럼 Hero Class를 @Component 밑으로 넣으면 안된다는 이야기입니다.


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


@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})


export class Hero {

  id : number;

  name : string;

}


export class AppComponent {

  title = 'Tour of Heroes';

  hero : Hero = {

    id : 1,

    name : 'windstorm'

  };

}


Hero Class 가 @Component 의 다음 Class 가 되면 해당 Component는

AppComponent class 가 아닌 Hero class 를 인식하기 때문에 주의하셔야 합니다.

보통은 Component 당 한개의 로직 클래스를 두기 때문에 이런 일은 거의 없습니다.


단순한 텍스트 였던 hero 변수를 새로운 객체로 만들었습니다.

hero : hero 는 hero 의 Type 이 Hero class 를 따른다는 것이고, 

내부 객체의 속성 역시 Hero Class와 같은 속성을 지닙니다.


여기서 Vscode와 TypeScript 의 조합을 왜 쓰는지 나옵니다.

현재 Hero class 의 name 속성의 Type 은 String 으로 지정했습니다.

만약 hero 변수에서 name 의 값을 number 로 넣게 되면 아래와 같이 됩니다.



Vscode 에서 해당 Type 이 잘못되었다고 알려줍니다.

여기서 id, name 을 제외한 다른 속성을 넣어도 당연히 잘못되었다고 나옵니다.

현재 hero 변수의 Type 은 Hero 이기 때문에 IDE 에서 체크하여 자동으로 잡아줍니다.

TypeScript의 장점입니다.


이제 해당 변수를 Template 에 바인딩 해야합니다.

/src/app/app.component.html 파일을 열어 아래와 같이 수정합니다.


<h1>{{title}}</h1>

<h2>{{hero.name}}</h2>


기존 hero 변수에서 hero.name 으로 수정했습니다.

hero 변수가 Hero Type 의 객체로 변했기 때문에 해당 객체의 name 속성을 가져온겁니다.


다음으로 해당 영웅의 이름뿐만 아니라 ID 역시 같이 보려고 합니다.

/src/app/app.component.html 파일을 수정합니다.


<h1>

{{title}}

</h1>

<h2>

{{hero.name}}

</h2>

<div>

<label>id:</label>

{{hero.id}}

</div>

<div>

<label>name:</label>

{{hero.name}}

</div>


수정한 화면을 확인해 보면 더욱 자세한 영웅의 정보를 알 수 있습니다.



이제 영웅의 정보를 수정하기 위한 작업을 해보겠습니다.

위 name 부분에서 영웅의 이름을 나타내는 부분이 label 이 아닌 TextInput 으로 바꿔서 이름을 변경해 보겠습니다.

먼저 View 부분을 수정하기 위해 /src/app/app.component.html 파일을 수정합니다.


<h1>

{{title}}

</h1>

<h2>

{{hero.name}} details!

</h2>

<div>

<label>id:</label>

{{hero.id}}

</div>

<div>

<label>name:</label>

<input value="{{hero.name}}" placeholder="name">

</div>


Label 부분을 Input 으로 변경하였습니다.

결과를 확인해 보면 텍스트를 입력하는 창이 생기고 해당 부분에 영웅의 이름이 들어가 있습니다.

하지만 여기서 영웅의 이름을 변경해도 h2 안에 있는 영웅의 이름은 같이 변경되지 않습니다.

여기에서 Angular 의 양방향 데이터 바인딩을 사용하여 영웅의 이름을 동시에 변경해 보겠습니다.

양방향 데이터 바인딩을 사용하기 위해서는 먼저 Angular 의 기본 제공 모듈 중 Forms 모듈을 사용해야 합니다.

해당 Forms 모듈을 불러오기 위해 /src/app/app.module.ts 파일에서 모듈을 import 시켜줘야 하지만 

Angular-cli 를 이용했기 때문에 이미 Forms 모듈을 사용할 수 있게 되어있습니다.


import { BrowserModule } from '@angular/platform-browser'; 

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

import { FormsModule } from '@angular/forms';

import { HttpModule } from '@angular/http';


import { AppComponent } from './app.component';


@NgModule({

    declarations: [

        AppComponent

    ],

    imports: [

        BrowserModule,

        FormsModule,

        HttpModule

    ],

    providers: [],

    bootstrap: [AppComponent]

})

export class AppModule { }


FormsModule 을 Import 하고 @NgModule 의 Import 속성에 FormsModule 이 이미 등록되어 있습니다.


준비가 되었으니 양방향 데이터 바인딩을 사용 해 보겠습니다.

사용법은 간단합니다.

[(ngModule)] = " 변수이름 " 으로 사용하면 됩니다.

/src/app/app.component.html 파일을 열어 수정합니다.


<h1>

{{title}}

</h1>

<h2>

{{hero.name}} details!

</h2>

<div>

<label>id:</label>

{{hero.id}}

</div>

<div>

<label>name:</label>

<input [(ngModel)]="hero.name" placeholder="name">

</div>


value = "{{hero.name}}" 에서 [(ngModel)] = "hero.name" 으로 수정했습니다.

이때 변수명에서 {{ }} 이중괄호는 제거해야합니다.

양방향 데이터 바인딩 설정이 끝났습니다.

저장 후 화면을 확인해 보겠습니다.



Text 창의 문구를 수정하면 h2 안의 hero.name 도 같이 변경됩니다.


이것으로 Hero Editor 의 첫 번째 챕터를 마치겠습니다.

Hero Editor 는 공식 홈페이지에 총 5개의 챕터로 나눠져 있습니다.


감사합니다.



REFERENCE

http://alexband.tistory.com/