Angular Seminar [한빛미디어 리얼타임 세미나]
-
Upload
woojin-joe -
Category
Technology
-
view
2.151 -
download
0
Transcript of Angular Seminar [한빛미디어 리얼타임 세미나]
발표에앞서다루는내용
• Angular와 연관된 프론트엔드 개발 생태계
• Angular�Framework의 아키텍처
• Angular�CLI와 Spring�boot를 사용한 Angular�
개발 과정 데모
발표에앞서다루지않는것
• 프론트엔드 웹 개발에 한정된 개념 혹은 지식
• TypeScript의 고유한 syntax�및 feature
• Angular�Framework 패키지별 API�사용 방법
• RxJs 및 Server�Side�Rendering�등 고급 주제
세미나의목표
• Self-Learning을 위한 마중물 붓기
• Angular�Framework�전체 구조 파악하기
• (어디가서 최신 프론트엔드 개발환경 아는 척 하기)
Angular
#1프론트엔드생태계변화와
Angular Framework
한빛미디어 리얼타임 세미나 05
옛날옛적에 JavaScript의탄생
• Brendan이말씀하시니 2주만에 JavaScript가생
기니라…
http://speakingjs.com/es5/ch04.html
SaviorforJavaScript
SaviorforJavaScript ECMA2015(ES6)
https://www.w3schools.com/js/js_versions.asp
JavaScript의변화
http://kangax.github.io/compat-table/es6/
http://slides.com/sakataa/deck-2#/
Node.js
https://twitter.com/BusyRich/status/494959181871316992
왜 Node.js ?
OS
JVM
Javacodes…
Browser
V8,Gecko,…
JScodes…
OSNode.js (V8)
JScodes…
Node.js &NPM
http://www.modulecounts.com
알아야할것이점점늘어난다…
프론트엔드관련생태계
http://joaoperibeiro.com/the-front-end-developer-spectrum
•패키지관리도구
• Bower
• NPM
• Yarn
주요도구분류 1/3
•자동화및 Task도구
• Grunt
• Gulp
• Yeoman
• NPM
주요도구분류 2/3
• Compiler (Preprocessor)
• CoffeeScript
• Babel
• Typescript
주요도구분류 3/3
RoughComparisonb/wtwoJ*
Java JavaScriptBuild&Deployment
Jenkins NPM,Gulp,Grunt
DependencyManagement,BuildConfiguration
Maven, Gradle,Ivy,… NPM, Yarn
RuntimeEnv. JVM(HotSpot,Rockit) V8,Gecko,Servo,…
Module화를향한노력
• 코드재사용성및범용화를위한노력
• CommonJS,AMD
• Webpack,ModuleinES6
• 자세한내용은…• http://d2.naver.com/helloworld/12864
• http://d2.naver.com/helloworld/591319
• http://d2.naver.com/helloworld/023981
Module화를향한노력
https://bertrandg.github.io/the-javascript-module-mess/
Angular
#2Angular Framework아키텍처이해하기
한빛미디어 리얼타임 세미나 05
Angular Framework
• Angular isa framework
• forbuilding clientapplications
• inHTMLandeitherJavaScriptoralanguage
like TypeScript thatcompilestoJavaScript.
Def1)Framework
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
Def2)ClientApplication
• View가있는모든 플랫폼
• Web,MobileWeb,nativemobile,andnativedesktop
Def3)TypeScript
• TypeScript isatyped supersetofJavaScript
• thatcompiles toplainJavaScript.
http://chariotsolutions.com/blog/post/angular2-starter-walkthrough-overview/
주요개념 1: Component
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 1: Component
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 1: Component
•모든 View는 Component로통한다.
주요개념 1: Component
•모든 View는 Component로통한다.
주요개념 1: Component
•모든 View는 Component로통한다.
주요개념 1: Component
import{Component}from'@angular/core';
@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent {title='app';}
주요개념 1: Component
import{Component}from'@angular/core';
@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent {title='app';}
ES6의Module import구문(Java의클래스 import와유사하지요? )
주요개념 1: Component
import{Component}from'@angular/core';
@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent {title='app';}
@는데코레이터데코레이터는대상에메타데이터제공및 Framework에게정보를주는역할을합니다.(Java의어노테이션같은… )
@Component에는많은메타데이터가들어갑니다.selector,template,templateUrl,providers,….
주요개념 1: Component
import{Component}from'@angular/core';
@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent {title='app';}
컴포넌트는 (ES6,TypeScript)Class입니다.
View에노출할값이나이벤트처리로직등을이클래스안에서작성합니다.
주요개념 1: Component
• 컴포넌트는 View를관리하는컨테이너와같다.
• AngularApp은컴포넌트트리를반드시갖는다.
• 컴포넌트트리의최상위루트컴포넌트를관례적으
로 AppComponent라한다.
• View를컴포넌트로나누는기준은없다.
• 재사용성
• 페이지단위
주요개념 2: Template
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 2: Template
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 2: Template
• View를구성하는 Angular-style의마크업
• View를구성하기위하여 Component와짝을이룸
• HTML을포함한 Angular에서제공하는다양한연
산자및 syntax를사용하여 View를구성하는코드
를작성
주요개념 2: Template
import{Component}from'@angular/core';
@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent {title='app';}
여기에 Template의경로를적었습니다.
주요개념 2: Template
import{Component}from'@angular/core';
@Component({
selector:'app-root',
template:'<h1>Angular!!!</h1>',
styleUrls:['./app.component.css']
})
exportclassAppComponent {
title='app';
}
template이간단한경우에는이렇게바로 template을쓰기도합니다.
주요개념 2: Template
<md-card><div class="contents"><md-input-container><input mdInput name="value" placeholder="사용자이름"
[(ngModel)]="userName" (ngModelChange)="onChange()"></md-input-container><button md-raised-button (click)="showWelcomeMsg()">입력</button><span class="welcome-msg">{{welcomeMsg}}</span>
</div></md-card>
Html+Angular의 Template구문으로이뤄집니다.처음보는속성들은다음개념설명에서알수있습니다.
https://github.com/not-for-me/hb-angular-first/blob/master/ch03/ng-welcome-msg-app/src/app/welcome-msg/welcome-msg.component.html
주요개념 3: ComponentLifecycle
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 3: ComponentLifecycle
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 3: ComponentLifecycle
• Component의생성과소멸주체
• 우리가아닌 AngularFramework
• Lifecycle을 Hooking하여내로직실행
주요개념 3: ComponentLifecycle
import{Component,OnInit,OnDestroy,DoCheck }from'@angular/core';
@Component({… })exportclassAppComponentimplementsOnInit,OnDestroy,DoCheck {
ngOnInit(){console.log('[ngOnInit]');}
ngOnDestroy(){console.log('[ngOnDestory]');}
ngDoCheck(){console.log('[ngDoCheck]');}}
주요개념 3: ComponentLifecycle
import{Component,OnInit,OnDestroy,DoCheck }from'@angular/core';
@Component({… })exportclassAppComponentimplementsOnInit,OnDestroy,DoCheck {
ngOnInit(){console.log('[ngOnInit]');}
ngOnDestroy(){console.log('[ngOnDestory]');}
ngDoCheck(){console.log('[ngDoCheck]');}}
Hooking할라이프사이클인터페이스를구현하겠다고선언합니다.
주요개념 3: ComponentLifecycle
import{Component,OnInit,OnDestroy,DoCheck }from'@angular/core';
@Component({… })exportclassAppComponentimplementsOnInit,OnDestroy,DoCheck {
ngOnInit(){console.log('[ngOnInit]');}
ngOnDestroy(){console.log('[ngOnDestory]');}
ngDoCheck(){console.log('[ngDoCheck]');}}
인터페이스에접두어로 ng를붙인메서드선언후,
필요한로직을작성합니다.
http://bit.ly/hb-ng-seminar-1
주요개념 4: Directive&Pipe
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 4: Directive&Pipe
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 4: Directive&Pipe
• View를동적으로만들어주는요소
• Directive• StructuralDirectives
• DOM구조를동적으로변화시킬때사용
• NgIf,NgFor,NgSwitch,…
• AttributeDirectives
• 컴포넌트, DOM요소의표현및동작방식을변경할때사용
• NgStyle,NgClass,…
주요개념 4: Directive&Pipe
• Pipe
• View에노출하는데이터를변형시킬때사용
• DatePipe,UpperCasePipe,CurrencyPipe,….
<p>SeminalDate:{{seminarDate |date:'YYYY-MM-dd'}}</p>
<p>SeminalDate:{{seminarDate |date|uppercase}}</p>
주요개념 4: Directive&Pipe
•실행예제
• http://bit.ly/hb-af-ng-if
• http://bit.ly/hb-af-ng-for
• http://bit.ly/hb-af-ng-switch
• http://bit.ly/hb-af-pipe
주요개념 5: DataBinding
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 5: DataBinding
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 5: DataBinding
• Component(+Template)과 View사이의연결고리
•모든일은 Angular가한다.우리는선언만할뿐
•절차적인방식 vs선언적인방식
• http://www.notforme.kr/archives/1698
주요개념 5: DataBinding
• 3가지바인딩:Property,Event,Two-wayBinding
주요개념 5: DataBinding
import{Component}from'@angular/core';
@Component({… })exportclassAppComponent {title='Hello,Angular';myData ='1234';inputSize='10';constructor(){}
showData(){alert(this.myData);}checkInput($event){console.log($event.target.value);}}
주요개념 5: DataBinding
import{Component}from'@angular/core';
@Component({… })exportclassAppComponent {title='Hello,Angular';myData ='1234';inputSize='10';constructor(){}
showData(){alert(this.myData);}checkInput(e){console.log(e.target.value);}}
View에바인딩할때필요한속성입니다.
Event바인딩을위해메서드도구현합니다.
주요개념 5: DataBinding
<h1>{{title}}</h1><inputtype="text"
[ngModel]="myData"[size]="inputSize"(keyup)="checkInput($event)">
<buttontype="button"(click)="showData()">showme</button>
주요개념 5: DataBinding
<h1>{{title}}</h1><inputtype="text"
[ngModel]="myData"[size]="inputSize"(keyup)="checkInput($event)">
<buttontype="button"(click)="showData()">showme</button>
컴포넌트의데이터를 View에 interpolation합니다.
주요개념 5: DataBinding
<h1>{{title}}</h1><inputtype="text"
[ngModel]="myData"[size]="inputSize"(keyup)="checkInput($event)">
<buttontype="button"(click)="showData()">showme</button>
Input요소의 size property에 inputSize를바인딩했습니다.
주요개념 5: DataBinding
<h1>{{title}}</h1><inputtype="text"
[ngModel]="myData"[size]="inputSize"(keyup)="checkInput($event)">>
<buttontype="button"(click)="showData()">showme</button>
showData(){alert(this.myData);}checkInput($event){console.log($event.target.value);}
Input의 keyup이벤트에checkInput메서드를바인딩했습니다.
button의 click이벤트에showData메서드를바인딩했습니다.
주요개념 5: DataBinding
<h1>{{title}}</h1><inputtype="text"
[ngModel]="myData"[size]="inputSize"(keyup)="checkInput($event)">
<buttontype="button"(click)="showData()">showme</button>
Input에 myData와양방향바인딩을선언했습니다.
주요개념 6: Service&DI
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 6: Service&DI
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
주요개념 6: Service&DI
• Service• 애플리케이션에서사용할값,함수등무엇이든 OK!
• 일반적으로 View와관련없는로직
• 비즈니스로직,애플리케이션공통코드, Data Store,…
• 단일책임원칙
• DependencyInjection• 우리가보는것은 Framework입니다.
• Angular에도의존성주입기능이!!!
주요개념 6: Service&DI
• DependencyInjection
• 우리가보는것은 Framework입니다.
• Angular에도의존성주입기능이!!!
• DI를위해필요한것
1. 의존성정보를어딘가기록하고
2. 의존하는쪽에서는 constructor에서 Arg.로받음
주요개념 6: Service&DI
import{Injectable}from'@angular/core';
@Injectable()exportclassTestDiService {constructor(){}
print(){console.log('hello');}}
컴포넌트에서의존할서비스클래스를간단히선언합니다.
주요개념 6: Service&DI
import{Component}from'@angular/core';import{TestDiService }from'./test-di.service';
@Component({…providers:[TestDiService]})exportclassAppComponent {constructor(privatetestService:TestDiService){}
foo(){this.testService.print();}}
서비스클래스에의존성이있는컴포넌트클래스선언합니다.
주요개념 6: Service&DI
import{Component}from'@angular/core';import{TestDiService }from'./test-di.service';
@Component({…providers:[TestDiService]})exportclassAppComponent {constructor(privatetestService:TestDiService){}
foo(){this.testService.print();}}
먼저사용할서비스 import합니다.
의존성정보를@Component메타데이터에선언합니다.*다음에설명하는 Module개념에서도선언가능
주요개념 6: Service&DI
import{Component}from'@angular/core';import{TestDiService }from'./test-di.service';
@Component({…providers:[TestDiService]})exportclassAppComponent {constructor(privatetestService:TestDiService){}
foo(){this.testService.print();}}
생성자에서 Parameter로선언하면Angular가해당인스턴스를주입합니다.
주요개념 6: Service&DI
import{Component}from'@angular/core';import{TestDiService }from'./test-di.service';
@Component({…providers:[TestDiService]})exportclassAppComponent {constructor(privatetestService:TestDiService){}
foo(){this.testService.print();}}
주입받은서비스를사용할수있습니다.
주요개념 6: Service&DI
• DI를사용하는이유
• 객체간의결합도낮추기 (Framework에게맡겨줘)
• 단일인스턴스보장받기
• 서비스클래스를애플리케이션전역에서사용하는
MemoryDB,MessageBus등으로쓸수있어요~~
주요개념 7:Module
• ES6에서말하는모듈이아님
• 지금까지설명했던 Angular의요소들을하나로담는
컨테이너
• Angular Framework의많은기능은모듈단위로제공
• FormsModule,ReactiveFormsModule,RouterModule,
HttpModule,…
주요개념 7:Module
import{BrowserModule }from'@angular/platform-browser';import{NgModule }from'@angular/core';import{AppComponent }from'./app.component';import{TestDiService }from'./test-di.service';
@NgModule({declarations:[AppComponent ],imports:[BrowserModule ],providers:[TestDiService ],bootstrap:[AppComponent ]})exportclassAppModule {}
주요개념 7:Module
import{BrowserModule }from'@angular/platform-browser';import{NgModule }from'@angular/core';import{AppComponent }from'./app.component';import{TestDiService }from'./test-di.service';
@NgModule({declarations:[AppComponent ],imports:[BrowserModule ],providers:[TestDiService ],bootstrap:[AppComponent ]})exportclassAppModule {}
NgModule데코레이터가Angular의모듈을의미합니다.
모든 AngularApp.반드시최소하나의모듈을갖습니다.(관례적으로 AppModule이라명명)
주요개념 7:Module
import{BrowserModule }from'@angular/platform-browser';import{NgModule }from'@angular/core';import{AppComponent }from'./app.component';import{TestDiService }from'./test-di.service';
@NgModule({declarations:[AppComponent ],imports:[BrowserModule ],providers:[TestDiService ],bootstrap:[AppComponent ]})exportclassAppModule {}
필요한모듈을 import할수있습니다.
주요개념 7:Module
import{BrowserModule }from'@angular/platform-browser';import{NgModule }from'@angular/core';import{AppComponent }from'./app.component';import{TestDiService }from'./test-di.service';
@NgModule({declarations:[AppComponent ],imports:[BrowserModule ],providers:[TestDiService ],bootstrap:[AppComponent ]})exportclassAppModule {}
모듈에담을요소는 declarations에선언해야합니다.
최초진입점인루트컴포넌트는bootstrap에명시해야합니다.
주요개념 7:Module
import{BrowserModule }from'@angular/platform-browser';import{NgModule }from'@angular/core';import{AppComponent }from'./app.component';import{TestDiService }from'./test-di.service';
@NgModule({declarations:[AppComponent ],imports:[BrowserModule ],providers:[TestDiService ],bootstrap:[AppComponent ]})exportclassAppModule {}
모듈레벨에서의존성주입선언도가능합니다.(컴포넌트에선언하는것보다모듈에선언한는것을권장합니다.)
Angular에서제공하는 package
• @angular/common
• @angular/compiler(@compiler-cli)
• @angular/core
• @angular/forms
• @angular/http
• @angular/platform-browser(platform-browser-dynamic)
• @angular/palatform-server
• …
Angular에서제공하는주요Module
• CommonModule:Angular에서제공하는각종지시자등을포함하는기본모
듈
• BrowserModule:웹에서실행할때필요한기본모듈,CommonModule을내
장하고있음
• FormsModule,ReactiveFormsModule:폼구성에필요한지시자등을제공,ngModel을쓰려면반드시필요
• HttpModule,JsonpModule:ajax호출과관련된서비스클래스등을제공
• BrowserAnimationsModule:브라우저의애니메이션처리(css) API를제공
Angular를구성하는요소들
ComponentLifeCycle
ViewComponent
Service
DependencyInjection
TemplateDirective
Pipe
DataBinding
Metadata
Angular
#3Angular (CLI) – SpringBoot
데모세션
한빛미디어 리얼타임 세미나 05
AngularCLI
• Angular프로젝트를 CLI에서쉽게구성/개발할수있도록도와주는도
구
• Google에서관리하는오픈소스는아님!
• Google에서는추후 Bazel +Clouser기반의빌드도구가나올수도있
음
• (2017년 7월)현재까지는 Angular개발환경셋팅에가장좋은도구
• 설치: npm install-g@angular/cli
AngularCLI+SpringBoot
Frontend폴더에 angularsource가있습니다.
AngularCLI+SpringBoot
Frontend폴더에 angularsource가있습니다.
"apps": [{"root": "src","outDir": "../resources/static","assets": [
"assets","favicon.ico"
],
.angular-cli.json에빌드결과물의위치를Boot의 static으로지정합니다.
Build과정
• Build시에는 frontend-maven-plugin을사용
• https://github.com/eirslett/frontend-maven-plugin
<groupId>com.github.eirslett</groupId><artifactId>frontend-maven-plugin</artifactId><version>${frontend-plugin.version}</version><configuration><workingDirectory>src/main/frontend</workingDirectory><nodeDownloadRoot>https://nodejs.org/dist/</nodeDownloadRoot><nodeVersion>${node.version}</nodeVersion><npmVersion>${npm.version}</npmVersion><installDirectory>target</installDirectory>
</configuration>
<executions><execution><id>installnodeandnpm</id><goals><goal>install-node-and-npm</goal></goals><phase>generate-resources</phase>
</execution><execution><id>npm install</id><goals><goal>npm</goal></goals><configuration><arguments>install</arguments><installDirectory>target</installDirectory>
</configuration></execution><execution><id>angularclibuild</id><goals><goal>npm</goal></goals><phase>generate-resources</phase><configuration><arguments>runbuild</arguments>
</configuration></execution>
</executions>
감사합니다.