잊지 않겠습니다.

angular cli

angularjs2 2016. 9. 21. 09:37

Angular-Cli

google에서 angular2와 같이 내놓은 angular2를 위한 cmd tool입니다. cmd tool중 가장 유명한 yo와 거의 동일한 기능을 제공합니다. 아직 beta version이기 때문에 발전의 여지는 많이 보이긴 하지만, angular2 application을 개발하기 위해서는 제 생각에는 반드시 angular cli를 통해서 개발 할 필요가 있습니다.

개인적인 이유의 근거는 다음과 같습니다.

  1. 표준 tool로 만들었기 때문에 모든 문서는 angular cli를 기본으로 나올 가능성이 높습니다.
  2. stackoverflow 와 같은 질의 응답 사이트의 내용 역시 angular cli를 기본으로 이야기하고 있습니다.
  3. third party tool역시 angular cli를 기반으로 나오기 쉽습니다.
  4. webpack을 기반으로 구성되어, 최적의 site를 만들기 좋습니다.
  5. 역으로 angular cli를 사용하지 않고, 직접 webpack 등의 설정을 하게 될 경우에 너무 힘듭니다. 진입장벽이 높아집니다.

angular cli는 기본적으로 다음 기능들을 가지고 있습니다.

  1. project 초기 생성
  2. component, service, pipe, directive 등의 생성
  3. gulp, grunt와 같은 build tool의 제공.
  4. scss, less와 같은 css preprocessor가 모두 지원

기본적으로 1.0.0-beta.15부터 webpack과 통합되어 있기 때문에 webpack에 대한 기본 지식이 있으면 좋습니다.

설치

npm install -g angular-cli

기타 tool들과 마찬가지로 npm을 이용해서 설치합니다. yo와는 다르게 다른 plugin들이 아직 제공되고 있지는 않군요.

project 초기 생성

ng new {{Project이름}}

위 command를 이용하면 Project이름으로 새로운 folder가 하나 생성되고, 기본적인 application 이 구성됩니다.

cd {{Project이름}} ng serve

를 실행하면 기본적인 angular2 application이 만들어집니다.

├── angular-cli.json ├── e2e │   ├── app.e2e-spec.ts │   ├── app.po.ts │   └── tsconfig.json ├── karma.conf.js ├── node_modules ├── package.json ├── protractor.conf.js ├── README.md ├── src │   ├── app │   ├── assets │   ├── environments │   ├── favicon.ico │   ├── index.html │   ├── main.ts │   ├── polyfills.ts │   ├── styles.css │   ├── test.ts │   ├── tsconfig.json │   └── typings.d.ts └── tslint.json

folder는 e2e와 src가 만들어지는데, e2e는 end to end test code가 위치하는 곳이고 개발은 주로 src에서 이루어지게 됩니다. yo에서는 이렇게 생성된 json 파일들을 조금 뜯어볼 필요성이 있는데, angular cli의 경우에는 거의 그럴 필요성이 느껴지지 않습니다. e2e 테스트를 위한 protractor.conf.js파일을 제외하면, 사용자가 건드릴 만한 파일들은 없습니다.

src에 만들어진 file 구성을 보면 component, spec, css, html 이 모두 갖추어져 있는것을 볼 수 있습니다. angular-cli는 개발자에게 component와 그에 따른 view file 들, 즉 css와 html이 같이 있는 구조를 강제합니다. 대부분의 angular2 tutorial에서 그리했듯이요. 기본적으로 만들어진 file의 내용은 다음과 같습니다.

import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-info', templateUrl: './info.component.html', styleUrls: ['./info.component.css'] }) export class InfoComponent implements OnInit { constructor() { } ngOnInit() { } }

매우 간단하지만, 타이핑이 귀찮은 것들은 많이 들어가 있는것을 볼 수 있습니다.

component, service, pipe, directive 생성

ng g {{type}} {{name}}

을 통해, 각각의 항목들을 만들어낼 수 있습니다. 여기서 재미있는것은 만약에 ng g component home.component를 통해 생성을 하면 /src/home folder가 기본으로 생깁니다. 이는 root folder에 너무 많은 파일들을 놓지 않으려는 배려로 볼 수 있겠네요. cmd를 통해서 생성하는 것들은 다음과 같습니다.

ScaffoldUsage
Componentng g component my-new-component
Directiveng g directive my-new-directive
Pipeng g pipe my-new-pipe
Serviceng g service my-new-service
Classng g class my-new-class
Interfaceng g interface my-new-interface
Enumng g enum my-new-enum

생성된 Component들은 모두 app.module.ts의 declarations에 기본적으로 추가되어 있습니다. 타 객체들은 추가되어있지 않으니, 상황에 따라 Component에 추가하는 것이 필요합니다.

route 지원

안타깝게도 angular-cli는 route를 생성하는 것을 지원하지 않습니다. 개발 방향을 잡고 있다니, 추후를 기대해봐도 좋을것 같습니다.

실행

ng serve

명령어로 실행이 가능합니다. 기본적으로 4200 port를 이용해서 처리되며, 파일 변경시 webpack watch를 통해 다시 build가 됩니다.

Proxy 설정

web application을 개발하게 되면 필연적으로 필요하게 되는 것이 Proxy입니다. 내부내에서 타 URL로 proxy를 통해 API를 호출하기 위해서는 내부 Proxy설정이 필요합니다. 이를 angular cli에서는 --proxy-config를 통해 해결하고 있습니다.

먼저, 기본적으로 angular cli에서 사용되는것은 webpack입니다. webpack dev server 설정에서의 proxy설정 방법과 완전 동일합니다. 그런데, webpack의 경우에는 webpack.config.js파일이 존재합니다. 그럼 angular cli는? 폴더의 어느곳을 뒤져봐도 위 파일은 존재하지 않습니다. angular cli는 webpack을 철저하게 wrapping해서 보여주기 때문이지요.

proxy를 구성하기 위해서는 추가 파일을 생성해서 처리해야지 됩니다. proxy.json파일을 따로 생성해서 처리하면 됩니다. 다음은 제 proxy.json파일입니다.

"/fms-api/v2"

2개의 proxy를 구성하였고, 구성된 proxy.json을 통해 실행시키기 위해서는 다음 cmd를 사용하면 됩니다.

ng serve --proxy-config proxy.json

이렇게 하면 실행창에 다음과 같은 구문이 나타납니다.

ykyoon@ykyoon ~/dev/code/cli-test1/my-dream-app $ ng serve --proxy-config proxy.json Could not start watchman; falling back to NodeWatcher for file system events. Visit http://ember-cli.com/user-guide/#watchman for more info. ** NG Live Development Server is running on http://localhost:4200. ** 10% building modules 2/2 modules 0 active[HPM] Proxy created: /fms-api/v2 -> http://localhost:8000 [HPM] Proxy rewrite rule created: "/fms-api/v2" ~> "" [HPM] Proxy created: /socket.io -> http://localhost:5000 4265ms building modules

Proxy에 설정에 대한 문서는 webpack dev server 설정과 동일합니다.

3rd party library

lodash

개인적으로는 jquery보다 더 필요한것이 이젠 lodash입니다. lodash 추가는 일반적으로 우리가 알고 있는 npm install lodash --save로 하는 것이 아니라 다음 command를 이용해서 해줘야지 됩니다.

npm install @types/lodash --save

그리고 lodash를 사용하고자 하는 곳에서 다음과 같이 사용합니다.

import * as _ from 'lodash'

jquery & bootstrap

jquery의 경우에는 조금 다릅니다. jquery의 경우에는 근간에는 거의 모든 외부 library들이 먼저 jquery가 추가된 후에 동작되는 것이 일반적인데, webpack에서 주로 사용하는 방식으로 import를 이용하면 이를 반영할수가 없습니다. 이렇게 먼저 추가되어야지 되는 library들이 있는 경우, angular-cli.json파일을 수정할 필요가 있습니다.

먼저 npm을 이용해서 jquery와 bootstrap을 추가합니다.

npm install jquery --save npm install bootstrap@next --save //bootstrap version 4

다음, script항목으로 들어가 추가되어야지 될 js파일을 순서대로 넣어줍니다.

"scripts": [ "../node_modules/jquery/dist/jquery.js", "../node_modules/tether/dist/js/tether.js", "../node_modules/bootstrap/dist/js/bootstrap.js" ],

마지막으로 styles에 bootstrap을 추가하면 완료됩니다.

"styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.css" ],

Summary

angular-cli는 매우 강력한 tool입니다. 또한 angular2 개발 방법의 표준을 제공하고 있습니다. 이는 강력하지는 않지만, 많은 3rd party library와 사용자들에게 영향을 주게 될 것입니다. 다른 3rd party library들의 사용방법이 angular-cli를 기준으로 문서가 만들어질 가능성이 매우 높습니다.

Posted by Y2K
,

angular2 animation

angularjs2 2016. 9. 13. 16:45

angular2에서의 animation은 state의 변경으로 제어가 가능합니다. 기존의 css를 지정해주었던 것에서 많은 변화가 생긴것이지요.

animation을 사용하기 위해서는 다음 모듈들을 import시켜야지 됩니다.

import { Component, Input, trigger, state, style, transition, animate } from '@angular/core';

후에 @Component에서 animations를 다음과 같이 정의합니다.

animations: [ trigger('showDetailed', [ state('summary', style({ height: '0px', display: 'none' })), state('detailed', style({ height: '250px', display: 'inherit' })), transition('summary <=> detailed', animate(250)), ]) ]

각 항목은 다음과 같습니다.

  • trigger(name): state 이름을 정합니다.
  • state(stateName): state의 상태이름을 지정하고, 상태이름일때의 style 를 지정합니다.
  • transaction: state 상태의 변경시에 동작할 animation을 지정합니다. 상태는 =><=> 을 지정합니다.

angular2에서의 animation은 상태의 변화시에 동작 이라고 정의하면 이해하기 쉽습니다.

간단히 showDetailed trigger의 summary와 detailed 상태의 변화에 있어서 summary일때의 최종 style과detailed상태일때의 최종 style을 지정해주고, state의 변경시에 발생되는 animation의 시간과 style을 정해주는 것으로 animation 효과를 넣을 수 있습니다.

주로 사용될 style들은 다음과 같습니다.

  • mouse-over: {transform: translateX(0) scale(1.1)}
  • mouse-leave: {transform: translateX(0) scale(1)}
  • show: { height: '200px', display: 'inherit' }
  • hide: { height: '0px', display: 'none' }

summary

angular2에서는 state라는 개념을 이용해서 animation을 넣어줍니다. 이는 객체의 상태 변화와 View에서의 animation을 적절히 조화시킬 수 있는 멋진 방법입니다. 그런데 이를 이용하기 위해서는 결국은 view component를 어떻게 잘 나누어서 설계하느냐에 대한 설계상의 이슈가 발생됩니다. 예전 개발 패턴대로 html 하나에 모두 때려 넣는것이 아닌, 하나하나의 Component로 Page 자체를 설계하는 View단에서의 객체지향적 개발 패턴이 필요합니다. 재미있어요.

Posted by Y2K
,

angular2 form

angularjs2 2016. 9. 13. 14:03

angular2 form

기존 angularjs에서 문제가 되었던 form이 크게 향상되었습니다. 기존 form의 문제점은 다음과 같습니다.

  1. form의 생성시기를 알 수 없습니다. div tag를 통해서 생성되는 ng-form은 생성시기를 알 수 없기 때문에, form을 검사하기 위해서는 null error를 꼭 check하는 것이 좋습니다.
  2. form error text가 html에 담긴다. form에서 발생되는 error를 표시하는 방법이 모두 html에 기술되어야지 됩니다. 이에 대한 구현의 문제는 html이 과도하게 길어지는 문제가 발생하게 되고, ng-if의 남발이 발생하게 됩니다.

angular2는 NgForm의 제어 영역을 component로 이동시켜서 기존의 html에서 제어되는 것이 아닌 component에서 제어되는 것으로 구현을 변경하였습니다. 물론, 기존과 같은 패턴 역시 사용가능합니다.

Form Validation - Old Pattern

기존 ngForm을 이용하는 방법과 거의 유사합니다.

<form #heroForm="ngForm" (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="name">Name</label> <input type="text" id="name" name="name" [(ngModel)]="hero.name" #name="ngModel" class="form-control" required minlength="4" maxlength="24"> <div *ngIf="name.errors && (name.dirty || name.touched)" class="alert alert-danger"> <div [hidden]="!name.errors.required"> Name is required </div> <div [hidden]="!name.errors.minlength"> Name must be at least 4 characters long. </div> <div [hidden]="!name.errors.maxlength"> Name cannot be more than 24 characters long. </div> </div> </div>
export class HeroFormTemplate1Component { powers = ['Really Smart', 'Super Flexible', 'Weather Changer']; hero = new Hero(18, 'Dr. WhatIsHisWayTooLongName', this.powers[0], 'Dr. What'); submitted = false; active = true; onSubmit() { this.submitted = true; } addHero() { this.hero = new Hero(42, '', ''); } }

각 form의 이름을 이용하고 [(ngModel)]을 이용해서 model과 값을 binding시켜 사용합니다. 여기서 주의할 점은 #name입니다. 이는 꼭 ngModel을 적어줘야지 되며, ngModel을 이용해서 heroForm과 binding이 되게 됩니다.

이 code의 최고 문제는 html에 error message가 그대로 노출된다는 점입니다. 이를 해결해주기 위해서는 다음과 같이 구성합니다.

Form Validation - new Pattern

새로운 패턴에서 확인할 점은 NgForm의 생성과 Error Message의 관리 포인트가 Component로 넘어왔다는 점입니다. 먼저 Component에서 FormBuilder를 Import합니다.

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

그리고, ngOnInit에서 FormGroup을 생성시켜줍니다.

constructor(private fb: FormBuilder) { } ngOnInit(): void { this.buildForm(); } buildForm(): void { this.heroForm = this.fb.group({ 'name': [this.hero.name, [ Validators.required, Validators.minLength(4), Validators.maxLength(24), ] ], 'alterEgo': [this.hero.alterEgo, [ Validators.required ]], 'power': [this.hero.power, Validators.required] }); this.heroForm.valueChanges .subscribe(data => this.onValueChanged(data)); this.onValueChanged(); // (re)set validation messages now }

FormBuilder.group은 각 Form element name에 따른 Validators를 갖습니다. Form Validation 조건들을 각 Component에서 처리가 가능해지는 것입니다. 또한 각 error에 대한 message 처리 역시 Component에서 가능하게 됩니다. 이는 위 코드 중 onValueChanged에서 처리 가능합니다.

onValueChanged(data?: any) { if (!this.heroForm) { return; } const form = this.heroForm; for (const field in this.formErrors) { this.formErrors[field] = ""; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; for (const key in control.errors) { this.formErrors[field] += messages[key] + " "; } } }
<form [formGroup]="heroForm" *ngIf="active" (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="name">Name</label> <input type="text" id="name" class="form-control" formControlName="name" required> <div *ngIf="formErrors.name" class="alert alert-danger"> {{ formErrors.name }} </div> </div> <div class="form-group"> <label for="alterEgo">Alter Ego</label> <input type="text" id="alterEgo" class="form-control" formControlName="alterEgo" required> <div *ngIf="formErrors.alterEgo" class="alert alert-danger"> {{ formErrors.alterEgo }} </div> </div> <div class="form-group"> <label for="power">Hero Power</label> <select id="power" class="form-control" formControlName="power" required> <option *ngFor="let p of powers" [value]="p">{{p}}</option> </select> <div *ngIf="formErrors.power" class="alert alert-danger"> {{ formErrors.power }} </div> </div> <button type="submit" class="btn btn-default" [disabled]="!heroForm.valid">Submit</button> <button type="button" class="btn btn-default" (click)="addHero()">New Hero</button> </form>

CustomeValidation 처리

CustomValidation의 경우에는 특수한 함수 형태를 반환해야지 됩니다. ValidatorFn을 반환하는 함수를 작성하고, 그 함수를 FormGroup.group 함수에 Binding시켜주면 됩니다.

import { ValidatorFn } from '@angular/forms'; forbiddenNameValidator(nameRe: RegExp): ValidatorFn { return (control: AbstractControl): { [key: string]: any } => { const name = control.value; const no = nameRe.test(name); return no ? { 'forbiddenName': { name } } : null; }; } this.heroForm = this.fb.group({ 'name': [this.hero.name, [ Validators.required, Validators.minLength(4), Validators.maxLength(24), this.forbiddenNameValidator(/bob/i) ] ], 'alterEgo': [this.hero.alterEgo, [ Validators.required ]], 'power': [this.hero.power, Validators.required] });

Summary

angular2에서의 FormValidation은 많은 발전을 가지고 왔습니다. 가장 큰 변화는 Component에서 Error Message 및 조건들을 관리하기 편해졌다는 것입니다. 기존 html에서 처리하는 방법 역시 가지고 있지만, 개인적으로는 최대한 사용하지 않는것이 좋아보입니다.

또한, 다국어 처리에 있어서도 더 나은 방법이 될 수 있습니다.

Posted by Y2K
,