ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 4장) Angular 2 -HeroEditor- (1)
    Angular 2017. 1. 5. 17:21


    본격적으로 The Hero Editor 를 만듭시다.

    먼저 간단하게 메인페이지에 새로운 글을 삽입해봅시다. 

    /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';
    }
    


    이제 제대로 바인딩 되었는지 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 당 1개의 로직클래스를 두기 때문에 이런 일은 잘 없다고 보면 되지만 

    혹시나 해서 알아두면 좋잖아요  헤헤 


    다시 본론으로 

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

    hero : Hero  는 hero 의 Type 는 Hero class 를 따른다는 것 이고 , 내부 객체의 속성 역시 Hero Class 와 같은

    속성을 지닙니다.  자 여기서 TypeScript 의 장점이 하나 나옵니다. 

    현재 Hero class 의 name 속성의 Type 는 String 으로 지정해 두었습니다.  헌데 hero 변수에서 만약  

    name 의 값을 number 로 넣게 되면 어떻게 될까요? 

    그림과 같이 Vscode 에서 해당 Type 가 잘못되었다고 알려줍니다. 

    여기서 id , name 외의 다른 속성을 넣어도 당연히 잘못되었다고 나옵니다. 현재 hero 변수의 Type 는 Hero 이기 때문에 

    이 역시 다 IDE 에서 체크하여 잡아줍니다. 

    여러분 TypeScript + Vscode 꿀 조합 꼭 쓰세요 


    이제 해당 변수를 Template 에 바인딩 해야겠죠?  

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

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


    기존 hero 변수에서 hero.name 으로 변경되었습니다. 

    당연히 hero 변수가 이젠 Hero Type 의 객체로 변했기 때문에 해당 객체의 name 속성을 가져오는 

    거라는 건 길을 지나가던 12살 꼬맹이도 알 수 있습니다.(?) 


    이제 해당 영웅의 이름뿐만 아니라 ID 역시 같이 보고 싶습니다. 

    /src/app/app.component.html 파일을 변경 해 줍시다. 

    
    <h1>
      {{title}}
    </h1>
    <h2>
      {{hero.name}} details!
    </h2>
    <div>
      <label>id:</label>
      {{hero.id}}
    </div>
    <div>
      <label>name:</label>
      {{hero.name}}
    </div>
    


    이제 화면을 확인해 보면 더욱 Detail 하게 영웅의 정보를 알 수 있습니다. 

    이제 보여주는 건 됬으니 영웅의 정보를 수정하기위한 작업을 해봅시다. 

    위 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 의 Imports 속성에 FormsModule 이 이미 등록되어있는 걸 

    확인 할 수 있습니다. 


    그럼 바로 양방향 데이터 바인딩을 사용 해 봅시다. 

    사용법은 간단합니다.  [(ngModel)] = "변수이름" 으로 사용하면 됩니다. 

    /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}}  에서 [(ng-model)] = "hero.name" 으로 변경 되었습니다.

    * 변수명에서 당연히 {{}} 는 제거되어야 합니다. 

    이제 양방향 데이터 바인딩 설정이 끝났으니 저장하고 직접 확인 해 봅시다. 

    Text 창의 문구를 바꿔보면 


    h2 안의 hero.name 도 같이 바뀌는 걸 확인 할 수 있습니다. 

    사용하기 정말 편리하죠?  

    여기까지 Hero Editor 의 첫번째 챕터가 끝났습니다.  

    공식홈페이지에서 보면 총 5챕터로 나뉘어져 있으니 금방 끝나겠네요 호호 

    그럼 20000 


    * 드디어 코드 표현방식을 바꿨습니다. 뭔가 더 깔끔하네요 후후 




    댓글