본문 바로가기
블로그 이미지

방문해 주셔서 감사합니다! 항상 행복하세요!

  
   - 문의사항은 메일 또는 댓글로 언제든 연락주세요.
   - "해줘","답 내놔" 같은 질문은 답변드리지 않습니다.
   - 메일주소 : lts06069@naver.com


앵귤러, 리엑트, 뷰/Angular Tutorial(new)

앵귤러 튜토리얼(Angular tutorial) - 30 : 모듈 활용

야근없는 행복한 삶을 위해 ~
by 마샤와 곰 2020. 9. 22.

저번시간까지 우리는 모듈과 라우터의 관계에 대해서 살펴보았습니다.
라우터는 앵귤러에서 사용자의 요청에 따른 다양한 페이지를 보여주기 위해 존재하는 기능이며, 개발자 입장에서는 다양한 모듈과 라우터를 통해서 협업을 좀 더 쉽게 해 주는 기능 입니다.


이번시간에는 우리가 여태껏 사용한 FormsModule이나 BrowserModule등 모듈에서 다른 모듈, 즉 라이브러리처럼 동작하는 모듈은 어떻게 만드는지 한번 살펴 보겠습니다.
새로운 프로젝트를 생성하여 줍니다.

ng new fiveStudy

프로젝트를 만들었습니다. 라우팅 여부는 Y로 합니다.

 

이번에도 모듈에서 라우팅 기능이 포함된 형태로 프로젝트를 생성하여 줍니다.
app컴포넌트html 파일은 라우터와 관련된 테그만 남기고 전부 제거하여 줍니다.

불필요한 화면을 제거하기 위해 라우터 테그만 남깁니다.

 

다음으로 동작할 컴포넌트를 추가하겠습니다.
컴포넌트이름은 이번에는 쉽게 test로 하겠습니다.
ng g component test

라우팅한 모듈이 사용할 컴포넌트 입니다.

 

app-routing모듈은 줄여서 라우팅모듈이라고 하겠습니다.
라우팅모듈에 방금 생성한 test컴포넌트를 라우팅 해 주도록 합니다.
test요청에 대해서 test컴포넌트가 동작하게 합니다.
* 대상 : app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TestComponent } from './test/test.component';


const routes: Routes = [
  {path: 'test', component : TestComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


이제 실행하여봅니다.
test요청에 대해서 test컴포넌트가 동작하고 있습니다.

test요청에  test컴포넌트가 동작 합니다.

 

여기까지는 라우팅과 관련된 내용입니다.

복습(?) 차원에서 한번 내용을 훑어 보았습니다.


이제 그러면 라이브러리처럼 사용할 수 있는 모듈을 제작하여 보겠습니다.
모듈 이름은 특정 알림기능을 도와주는 모듈인 alert모듈이라고 하고 명령어를 통해 생성하여 줍니다.

ng g module alert

 

그리고 alert모듈이 사용할 컴포넌트를 제작하겠습니다.
ng g component alert

 

이제 alert모듈을 살펴보겠습니다.

* 대상 : alert.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AlertComponent } from './alert.component';

@NgModule({
  declarations: [AlertComponent],
  imports: [
    CommonModule
  ]
})
export class AlertModule { }

 

alert컴포넌트가 자연스럽게  declarations에 추가된 것을 볼 수 있습니다.

우리는 컴포넌트나 모듈을 만들 때 class를 기반으로 사용하였습니다.

이전에 살펴본 바와 같이 앵귤러의 기본구조는 class에 컴포넌트 또는 모듈 데코레이터등 데코레이터가 붙어있는 구조입니다!

기억이 가물가물하면 아래 링크를 통해 다시한번 살펴보고 오도록 합니다.

lts0606.tistory.com/331

 

이와 비슷한 방법으로 모듈에서 외부로 어떠한 기능을 전달하고자 할 때는 export라는 속성에 내보낼 대상을 사용합니다.

아래처럼 export를 추가하여봅니다.

* 대상 : alert.module.ts

* 대상 : alert.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AlertComponent } from './alert.component';



@NgModule({
  declarations: [AlertComponent],
  imports: [
    CommonModule
  ],
  exports : [AlertComponent]  //외부로 전달!
})
export class AlertModule { }

 

이렇게 만든 모듈은 alert컴포넌트가 외부로 전달되어집니다.
alert컴포넌트는 셀렉터(selector)가 "app-alert" 입니다.
그러므로 해당 모듈을 다른 모듈에서 사용하려면 alert 컴포넌트의 셀렉터(selector)를 사용해야 합니다.
해당 셀렉터를 이제 test컴포넌트에 붙여보겠습니다.
* 대상 : test.component.html

<p>test works!</p>
<p>얼럿 모듈이 들어왔습니까?</p>
<app-alert></app-alert>
<p>얼럿 모듈이 들어왔습니까?</p>

 

방금 만든 alert모듈은 우리가 만든 모듈이지만 아직 app모듈에 등록하지를 않았습니다.
app모듈에 alert모듈을 추가하여 봅니다.
* 대상 : app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { AlertModule } from './alert/alert.module';

@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    AlertModule,  //새로만든 얼럿 모듈입니다.
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

test로 다시 접속하여 화면을 살펴봅니다.

alert 모듈에서 등록한 alert컴포넌트가 동작하였습니다!!!

 

만약 오류가나거나 사진처럼 화면이 보이지 않는다면 서버를 중지 하였다가 다시 켜 주도록 합니다.
예전에 우리는 input과 output이라는 데코레이터를 통해서 컴포넌트간의 데이터를 주고받은적이 있었습니다.

기억이 안나면 아래 링크를 통해 확인하여 봅니다.

lts0606.tistory.com/351

 

동일한 방법으로 내용을 채워보겠습니다.
alert 컴포넌트에 아래처럼 수정하여 보겠습니다.

* 대상 : alert.component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.css']
})
export class AlertComponent implements OnInit {

  @Input() name : any;  //들어온 데이터
  @Output() sendToEvent = new EventEmitter<any>();  //보낼 데이터


  constructor() { }

  ngOnInit(): void {

  }

  //콜백용 함수, 이벤트 전달
  toastEvent(){
    this.sendToEvent.emit({text:'abcd', number : 1234});
  }

}

 

* 대상 : alert.component.html

<div *ngIf="name"> 
    {{name}} : <input type='button' value='이벤트 발생' (click)= 'toastEvent()'/>    
</div>    

 

name이라는 값이 존재하면 "이벤트발생"이라는 버튼이 동작하게 하였습니다.
그리고 해당 버튼은 click이벤트를 부여하였습니다.
자, test컴포넌트 html파일을 수정하여 보겠습니다.
* 대상 : test.component.html

<p>test works!</p>
<p>얼럿 모듈이 들어왔습니까 : {{test_name}}</p>
<input type='button' value='테스트' (click) ='test()' />
<app-alert [name] ='test_name' (sendToEvent)='getEvent($event)'></app-alert>

 

다음으로 이제 test컴포넌트를 수정하여 보겠습니다.

* 대상 : test.component.ts

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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  test_name : any;

  constructor() { }

  ngOnInit(): void {

  }

  test(){  //test_name값을 변경하는 함수 입니다.
    if(this.test_name){
      this.test_name = null
    } else {
      this.test_name = 'hello';
    }
  }

  getEvent(event){  //alert모듈으로부터 받은 내용입니다.
    console.log('alert 모듈한테 받았습니다 : ',event);
  }
}

 

컴포넌트간의 데이터를 주고 받는 방법이 모듈간에도 적용된 것을 볼 수 있습니다.
alert모듈에게 test컴포넌트에서 test_name값을 전달하여 주었고,
alert모듈의 exports에 해당하는 alert컴포넌트가 toastEvent함수를 통해서 test모듈에게 데이터를 다시 전달해주는 기능 입니다.

모듈에서 모듈로 데이터를 주고받았습니다.

 

export라는 기능을 활용하면 위 내용처럼 나만의 모듈을 따로 생성하여 라이브러리처럼 사용할 수 있습니다.
물론 데이터 공유 방법에서는 이전에 사용하였던 Observable객체를 활용한 특정 서비스를 만들어서도 가능 합니다.

이번시간에는 모듈을 라이브러리처럼, 독립된 영역으로 분리하여 사용하는 방법에 대해서 알아보았습니다.
다음시간에는 이전에 살펴보았던 디렉티브에 대해서 다시 살펴보겠습니다.

fiveStudy.zip
0.01MB

 

반응형
* 위 에니메이션은 Html의 캔버스(canvas)기반으로 동작하는 기능 입니다. Html 캔버스 튜토리얼 도 한번 살펴보세요~ :)
* 직접 만든 Html 캔버스 애니메이션 도 한번 살펴보세요~ :)

댓글