기본 콘텐츠로 건너뛰기

Angular 모듈(Module)

Angular 모듈(Module)

Angular 모듈(Module)

Angular의 모듈(Module)에 대해 알아보겠습니다.

1. 모듈 (Modue)

Angular의 모듈은 Angular의 컴포넌트, 디렉티브, 파이프, 서비스 등과 같이 관련이 있는 요소를 모은 하나의 단위를 의미합니다. 모듈은 다른 모듈과 결합할 수 있으며 Angular는 여러 모듈을 조합하여 하나의 애플리케이션을 구성합니다.

또한 모듈은 다른 모듈을 import 할 수 있습니다. Angular에서 제공하는 라이브러리 모듈이나 서드 파티 라이브러리도 import 하여 사용할 수 있습니다.

이러한 모듈성(Modularity)은 애플리케이션 개발에 있어서 중요한 의미를 갖습니다. 애플리케이션에 대한 요구사항이 많아지면서 코드의 복잡도가 높아짐에 따라 루트 모듈, 기능 모듈, 공유 모듈, 핵심 모듈 등으로 모듈을 분리하여 구성합니다. 이러한 특징은 모듈 간의 결합을 최소화하고 서로 연관있는 모듈간의 응집성을 극대화 해줍니다.

1.1 루트 모듈 (Root Module)

루트 모듈은 Angular 애플리케이션 최상위에 존재하는 모듈입니다. 컴포넌트, 디렉티브, 파이프, 서비스를 선언하거나 의존 라이브러리 모듈과 기능 모듈(하위 모듈)을 import 할 수 있습니다.

모든 애플리케이션은 루트 모듈을 가지고 있어야 하며 애플리케이션의 최상위에 위치하고 시작점의 역할을 합니다. 즉, 루트 모듈이 부트스트랩되면서 애플리케이션이 동작하게 됩니다.

루트 모듈은 일반적으로 AppModule 이라는 이름으로 생성되며 Angular CLI를 이용하여 프로젝트 생성시 app.module.ts 라는 파일로 생성됩니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 /* 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 { ChildComponent } from './child.component' ; @NgModule({ declarations: [ AppComponent, ChildComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule {} Colored by Color Scripter cs

1.2 @NgModule 데코레이터

Angular 애플리케이션의 모듈은 @NgModule 데코레이터가 적용된 클래스입니다. @NgModule 데코레이터는 함수이며 모듈의 설정 정보가 담긴 메타데이터 객체를 파라미터로 받아서 모듈을 생성합니다. 메타데이터는 declarations, imports, providers, bootstrap 등의 프로퍼티로 구성됩니다.

1 2 3 4 5 6 7 8 9 10 11 12 /* @NgModule Metadata */ @NgModule({ providers?: Provider[] declarations?: Array < Type < any > | any[] > imports?: Array < Type < any > | ModuleWithProviders | any[] > exports?: Array < Type < any > | any[] > entryComponents?: Array < Type < any > | any[] > bootstrap?: Array < Type < any > | any[] > schemas?: Array < SchemaMetadata | any[] > id?: string }) Colored by Color Scripter cs

다음은 메타데이터 객체의 주요 프로퍼티입니다.

프로퍼티 내용 providers 서비스(Injectable object)의 리스트를 선언. 루트 모듈에 선언된 서비스는 애플리케이션 전역에서 사용 가능. declarations 컴포넌트, 디렉티브, 파이프의 리스트를 선언. 모듈에 선언된 구성요소는 모듈 내에서 사용 가능. imports 의존 관계의 Angular 라이브러리 모듈, 기능 모듈(하위 모듈), 라우팅 모듈, 서드 파티 모듈 등을 선언. bootstrap 루트 모듈에서 사용하는 프로퍼티. 애플리케이션의 진입점(Entry point)인 루트 컴포넌트를 선언.

1.3 라이브러리 모듈 (Library Module)

라이브러리 모듈은 Angular에서 제공하는 built-in 모듈입니다. 라이브러리 모듈 패키지는 모듈의 집합체이며 필요한 모듈만 선택하여 import 할 수 있습니다.

Angular CLI를 이용하여 생성한 프로젝트의 package.json 파일을 보면 @angular 라이브러리 모듈이 포함되어 있는 것을 확인할 수 있습니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 /* package.json */ "dependencies" : { "@angular/animations" : "~8.2.11" , "@angular/common" : "~8.2.11" , "@angular/compiler" : "~8.2.11" , "@angular/core" : "~8.2.11" , "@angular/forms" : "~8.2.11" , "@angular/platform-browser" : "~8.2.11" , "@angular/platform-browser-dynamic" : "~8.2.11" , "@angular/router" : "~8.2.11" , "rxjs" : "~6.4.0" , "tslib" : "^1.10.0" , "zone.js" : "~0.9.1" } Colored by Color Scripter cs

다음은 라이브러리 모듈의 주요 구성요소에 대한 설명입니다.

@angular/common : 파이프, 디렉티브 관렴 모듈

@angular/core : 주요 데코레이터 및 핵심 모듈

@angular/forms : 폼 관련 디렉티브 및 모듈

@angular/http : HTTP 통신과 관련된 모듈

@angular/platform-browser : 브라우저 모듈

@angular/router : 라우터 관련 디렉티브 및 모듈

@angular/testing: 테스팅 관련 모듈

라이브러리 모듈은 앞서 살펴본 루트 모듈에서 BrowserModule, NgModule을 import한 것처럼 작성하여 사용합니다.

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

※ BrowserModule @angular/platform-browser 패키지의 BrowserModule은 CommonModule을 내부에서 import 합니다. 따라서 BrowserModule을 import 하면 별도의 추가적인 import 없이 CommonModule의 NgIf, NgFor와 같은 빌트인 디렉티브와 파이프의 사용이 가능합니다.

웹 애플리케이션의 경우 루트 모듈에서 BrowserModule을 import 하여 애플리케이션 전역의 컴포넌트 템플릿에서 빌트인 디렉티브와 파이프의 사용이 가능합니다. 루트 모듈을 제외한 다른 모듈은 CommonModule을 별도로 import 하여 사용합니다.

예를 들어, NgModel을 사용하려면 FormsModule을 improt 하고 HttpClient를 사용하려면 HttpClientModule을 import 하면 됩니다.

2. 모듈의 분리

애플리케이션의 복잡도가 증가하고 커짐에 따라 루트 모듈에 등록된 컴포넌트, 디렉티브, 파이프, 서비스도 함께 늘어나게 됩니다. 이렇게 루트 모듈에 여러 기능이 혼재되면 관리와 분업이 어려워지기 때문에 다음과 같이 기능 모듈, 핵심 모듈, 공유 모듈 등으로 모듈을 분리합니다.

모듈 내용 적용 대상 기능 모듈 관심사가 유사한 구성요소로 구성. 특정 화면 단위로 적용 공유 모듈 애플리케이션 전역에 공유한 구성요소로 구성. 기능 모듈에 의해 import 됨 애플리케이션 전역에서 사용되는 컴포넌트, 디렉티브, 파이프 등 핵심 모듈 애플리케이션 전역에 공통으로 사용할 구성요소로 구성. 루트 모듈에 등록하여 싱글턴으로 사용. 애플리케이션 전역에서 사용되는 서비스 ex) auth.service, auth.guard, data.service

간단한 예제를 통해 모듈의 분리에 대해 확인해보겠습니다. Angular CLI로 프로젝트를 생성한 후 아래와 같이 구조를 구성해줍니다.

2.1 루트 모듈 (Root Module)

애플리케이션의 시작점 역할을 하는 루트 모듈과 연관 파일은 다음과 같이 구성해줍니다.

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 /* 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' ; // HomeModule(기능 모듈) 등록 import {HomeModule} from './feature/home.module' ; // CoreModule(핵심 모듈) 등록 import {CoreModule} from './core/core.module' ; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HomeModule, CoreModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Colored by Color Scripter cs

1 2 3 4 5 6 7 8 9 10 11 12 13 /* app-routing.module.ts */ import {NgModule} from '@angular/core' ; import {Routes, RouterModule} from '@angular/router' ; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } Colored by Color Scripter cs

1 2 3 4 5 6 7 8 9 10 11 /* app.component.ts */ import {Component} from '@angular/core' ; @Component({ selector: 'app-root' , templateUrl: './app.component.html' , styleUrls: [ './app.component.css' ] }) export class AppComponent { } Colored by Color Scripter cs

1 2 3 /* app.component.html */ < app - home - component > < / app - home - component > cs

루트 모듈 AppComponent의 템플릿에서는 HomeComponent를 호출하도록 작성해줍니다.

2.2 기능 모듈 (Feature Module)

기능 모듈은 관심사가 유사한 구성요소로 만든 모듈입니다. 일반적으로 화면 단위를 기준으로 구성하며 루트 모듈과 마찬가지로 @NgModule 데코레이터를 사용하여 구성합니다.

예제에서는 home 화면을 담당하는 HomeComponent를 기능 모듈로 분리하여 다음과 같이 작성해줍니다.

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 /* home.module.ts */ import {NgModule} from '@angular/core' ; import {CommonModule} from '@angular/common' ; // SharedModule(공유 모듈) 등록 import {SharedModule} from '../shared/shared.module' ; // HomeComponent 등록 import {HomeComponent} from './home.component' ; @NgModule({ imports: [ CommonModule, SharedModule ], declarations: [ HomeComponent // HomeComponent 선언 ], providers: [], exports: [ HomeComponent // HomeComponent 공개 ] }) export class HomeModule { } Colored by Color Scripter cs

HomeModule은 루트 모듈이 아니므로 CommonModule을 import 해줍니다.

1 2 3 4 5 6 7 8 /* home.component.html */ < app - header - component [title] = "title" > < / app - header - component > < ul > < li > id: {{user.id}} < / li > < li > name : {{user. name }} < / li > < li > admin: {{user.admin}} < / li > < / ul > Colored by Color Scripter cs

템플릿에는 화면에서 header로 사용할 공유 모듈의 HeaderComponent를 추가해줍니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 /* home.component.ts */ import {Component, OnInit} from '@angular/core' ; import {UserService} from '../core/user.service' ; import {User} from '../core/user' ; @Component({ selector: 'app-home-component' , templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { public title = 'User Information' ; public user: User; constructor ( private userService: UserService) {} ngOnInit() { this.user = this.userService.getUser(); } } Colored by Color Scripter cs

2.3 공유 모듈 (Shared Module)

공유 모듈은 애플리케이션 전역에서 공유할 구성요소들로 구성한 모듈입니다. 주로 기능모듈에서 공통으로 사용할 내용들로 구성하며 애플리케이션 전역에서 사용하는 컴포넌트, 디렉티브, 파이프 등을 구성 대상으로 합니다.

루트 모듈은 기능 모듈을 import 하고 기능 모듈은 공유 모듈을 import 하여 사용합니다. 이렇게 모듈을 구성하면 모듈 선언을 간소화하여 기능 모듈의 중복을 제거할 수 있습니다.

예제에서는 페이지의 header를 담당하는 HeaderComponent를 공유 모듈로 분리하여 다음과 같이 작성해줍니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 /* shared.module.ts */ import {NgModule} from '@angular/core' ; import {CommonModule} from '@angular/common' ; // HeaderComponent 등록 import {HeaderComponent} from './header.component' ; @NgModule({ imports: [ CommonModule ], declarations: [ HeaderComponent // HeaderComponent 선언 ], providers: [], exports: [ HeaderComponent // HeaderComponent 공개 ] }) export class SharedModule { } Colored by Color Scripter cs

SharedModule 또한 루트 모듈이 아니므로 CommonModule을 import 해줍니다.

1 2 3 4 5 6 /* header.component.html */ < nav > < div class = "title" > {{title}} < / div > < a class = "user" href = "#none" > {{user. name }} < / a > < / nav > Colored by Color Scripter cs

1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* header.component.css */

nav { background-color : #4a4c88 ; overflow : hidden ; } .title , .user { line-height : 50px ; margin : 0 30px ; color : #fff ; text-decoration : none ; font-weight : bold ; text-transform : uppercase ; opacity : 0.7 ; } .title { float : left ; } .user { float : right ; font-style : italic ; } cs

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /* header.component.ts */ import {Component, OnInit, Input} from '@angular/core' ; import {UserService} from '../core/user.service' ; import {User} from '../core/user' ; @Component({ selector: 'app-header-component' , templateUrl: './header.component.html' , styleUrls: [ './header.component.css' ] }) export class HeaderComponent implements OnInit { @Input() public title: string; public user: User; constructor ( private userService: UserService) {} ngOnInit() { this.user = this.userService.getUser(); } } Colored by Color Scripter cs

애플리케이션 전역에서 사용하는 핵심 모듈의 UserService를 import하여 User를 초기화해줍니다.

2.4 핵심 모듈 (Core Module)

핵심 모듈은 애플리케이션 전역에서 공통으로 사용할 구성요소들로 구성한 모듈입니다. 공유 모듈과 유사하지만 루트 모듈에 등록하여 사용한다는 차이점이 있습니다. 싱글턴으로 동작하며 애플리케이션 전역에서 사용하는 data.service, auth.service, auth.guard 등을 대상으로 합니다.

핵심 모듈은 루트 모듈의 구성을 보다 간결하게 관리할 수 있도록 하는 것이 목적이며, 어떤 모듈에도 포함되지 않는 독립적인 요소들로 구성한 모듈입니다.

예제에서는 사용자 정보를 저장하는 UserService를 핵심 모듈로 분리하여 다음과 같이 작성해줍니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* core.module.ts */ import {NgModule} from '@angular/core' ; // UserService 등록 import {UserService} from './user.service' ; @NgModule({ imports: [], declarations: [], providers: [ UserService ], exports: [] }) export class CoreModule { } Colored by Color Scripter cs

CoreModule에서는 위와 같이 service만 등록하여 사용하므로 CommonModule을 import 하지 않아도 됩니다.

1 2 3 4 5 6 7 /* user.ts */ export interface User { id: number; name : string; admin: boolean; } cs

사용자 정보를 담을 User 타입의 인터페이스를 선언해줍니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* user.service.ts */ import {Injectable} from '@angular/core' ; // User interface 등록 import {User} from './user' ; @Injectable() export class UserService { public getUser(): User { return { id: 1 , name : 'harry' , admin: true }; } } Colored by Color Scripter cs

UserService에서는 @Injectable() 데코레이터를 사용하여 CoreModule의 provider에 등록해줍니다.

구성을 마친 후 실행하면 다음과 같은 페이지가 출력됩니다.

애플리케이션을 구성할 때 반드시 기능, 공유, 핵심 모듈로 구분해야하는 것은 아닙니다. 하지만 모듈을 적절하게 분리하는 것은 중복을 제거하여 코드의 양을 줄이고 복잡도를 줄여 생산성을 높이는데에 도움을 줍니다.

이상으로 Angular의 모듈(Module)에 대해 알아봤습니다.

※ 참고 문헌

이웅모 지음, 『Angular Essentials』, 루비페이퍼(2018), p510 ~ p531. 15. 모듈

skout90.github.io, 04. Angular 모듈, https://skout90.github.io/2017/07/12/Angular/4.%20Angular%20%EB%AA%A8%EB%93%88/

from http://freestrokes.tistory.com/97 by ccl(A)

댓글

이 블로그의 인기 게시물

[Angular] Router 라우터 정리

[Angular] Router 라우터 정리 Angular2 버전 이후를 기준으로 정리한 글입니다. 라우터는 URL을 사용하여 특정 영역에 어떤 뷰를 보여 줄지 결정하는 기능을 제공한다. 전통적인 서버사이드 렌더링을 하는 웹 사이트는 주소가 바뀔 때마다 서버에 전체 페이지를 요청하고 전체 페이지를 화면에 렌더링한다. 매 요청시 전체 페이지를 새로 랜더링하는 것은 비효율적이기 때문에 라우터를 이용하여 필요한 부분만 랜더링을 한다면 효율적일 것이다. 라우터는 URL에 해당하는 컴포넌트를 화면에 노출하고 네비게이션을 할 수 있는 기능을 가지고 있다. Router 구성 요소 Router – 라우터를 구현하는 객체이다. Navigate() 함수와 navigateByUrl() 함수를 사용하여 경로를 이동할 수 있다. RouterOulet – 라우터가 컴포넌트를 태그에 렌더링하는 영역을 구현하는 Directive이다. Routes – 특정 URL에 연결되는 컴포넌트를 지정하는 배열이다. RouterLink – HTML의 앵커 태그는 브라우저의 URL 주소를 변경하는 것이다. 앵귤러에서 RouterLink를 사용하면 라우터를 통해 렌더링할 컴포넌트를 변경할 수 있다. ActivatedRoute – 현재 동작하는 라우터 인스턴스 객체이다. Router 설정 라우터를 사용하기 위해서는 먼저 Router 모듈을 import 해야 한다. import { RouterModule, Routes } from '@angular/router'; 라우터에서 컴포넌트는 고유의 URL과 매칭된다. URL과 컴포넌트는 아래와 같이 Routes 객체를 설정하여 지정할 수 있다. 아래의 예에서는 디폴트 path에서는 MainComponent가 노출이 되고 product-list path에서는 ProductListComponent가 노출이 되도록 설정을 한 것을 볼 수 있다. const routes: Routes = [ { pa...

[Angular] Controller

[Angular] Controller Step02_controller.html // angular 모듈 만들기 var myApp = angular.module( "myApp" ,[]); // Ctrl1 이라는 이름의 컨트롤러 만들기 myApp.controller( "Ctrl1" ,[ "$scope" , function ($scope){ $scope. name = "김구라" ; $scope.clicked = function (){ alert ( "버튼을 눌렀네?" ); }; $scope.nums = [ 10 , 20 , 30 , 40 , 50 ]; }]); // Ctrl2 이라는 이름의 컨트롤러 만들기 myApp.controller( "Ctrl2" ,[ "$scope" , function ($scope){ $scope. name = "원숭이" ; $scope.friends = [ {num: 1 , name : "김구라" ,addr: "노량진" }, {num: 2 , name : "해골" ,addr: "행신동" }, {num: 3 , name : "원숭이" ,addr: "동물원" } ]; }]); 내이름은 : {{name}} 눌러보셈 {{tmp}} 너의 이름은 : {{name}} 번호 이름 주소 {{tmp.num}} from http://heekim0719.tistory.com/164 by ccl(A) rewrite - 2020-03-07 09:21:16

JQuery - $ 사용 유형.

JQuery - $ 사용 유형. 최근에 새로운 Javascript 프레임워크와 라이브러리들이 많이 등장했고 시장 점유율 또한 많이 변동 되었다고 한다. 특히 요새 대새는 Angular와 React라고들 한다. 그리고 Jquery 요즘 누가써? Jquery 퇴물이야 등등... 그런 이야기들을 종종 찾아볼 수 있는데, 유행은 돌고 돌듯이 결국 Jquery가 몰락할 일은 없다고 생각하는 바, 묵묵히 Jquery를 고집하기로 한다...ㅎㅎ 먼저 Jquery 교과서랄까.. 기본 문법을 배울 수 있는 링크를 걸어둔다. https://www.w3schools.com/jquery 여기서 기초들을 다 익힐 수 있다. 프로그래밍 문법을 한번이라도 봤다면 + - * / 같은 연산 while, for 등은 다 비슷하기 때문에 $ 사용법만 잘 알면 될 것 같다. $ syntax 사용유형 일단 기본적으로 $는 JQuery에서 미리 정해놓은 변수 값이다. : JQueryStatic 1. $( ) : JQueryObject 가장 많이 사용하는 형태이다. 괄호 안에 들어 갈 수 있는 것들은 클래스 이름, 아이디, 셀렉터 등이다. 예를 들어 $('p')이면 현재 html 페이지에 있는 모든 를 JqueryObject로 가져오겠다는 것이다. hide()는 제이쿼리 메서드이다. $('p')는 제이쿼리 오브젝트이기 때문에 제이쿼리 메서드를 사용할 수 있다. 그중의 하나인 hide()를 사용해 보았다. 결과이다. 에는 스타일이 적용이 되었다. 해당 태그에는 jquery의 메서드가 적용이 된 것을 확인할 수 있다. 2. $.함수 : 플러그인 개발 또는 기본 전역함수 플러그인을 개발 할 때나 Jquery가 갖고 있는 기본 전역함수들을 사용할 때 쓴다. 전역함수에는 여러개가 있는데 그중에 개인적으로 많이 쓰는 것은 $.ajax({}), $.each({}) 등이 있다. 이 함수들의 사용방법은 따...