블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2016. 1. 14. 08:23 Angular/Concept

이번에는 Angular2 Templating에 대한 Design Guide를 살펴본다. Angular1에서 Angular2로 오면서 살아남은 명칭중 하나는 Directive(지시자)이다. 지시자는 Angular 프레임워크에서 컴포넌트의 지위를 얻을 수 있는 방법을 제공했으나, Scope에 대한 격리 옵션과 모델들의 @/&/= 옵션, ControllerAs 등 문법적으로 알고 가야할 사항이 많아서 처음 접근하는 개발자에게 상당한 Learning Curve가 존재한다.




친숙함과 간결함 사이에서 (Familiarity vs Simplicity)


친숙함은 달콤하다. 지금 잘 알고 있는 것을 가지고 현재를 편하게 즐길 수 있도록 해준다. 하지만 변화에 둔하고 러닝커브가 높을 경우 신규로 알아야 할 사람들에게 많은 시간을 투자하게 만든다. 친숙함이 정말 친숙한 것인지 한번 더 돌아보고 주위 사람들이 왜(Why) 어려워 하고 어떻게(How)하면 쉽고 빠르게 익히고 널리 사용할 수 있도록 무엇(What)으로 만들 수 있을지 기술 리더는 고민해 보아야 한다. 


간결함은 하는 역할이 명확하여 쉽게 이해한다. 배움의 시간을 단축시켜주고 즐거움을 줄 수 있다. 그러나 복잡함을 간결하게 표현하기 위해서는 함축적이다. 따라서 그 내면에 있는 내용을 이해하고 쓰면 더 많은 생각들을 읽을 수 있다. 따라서 간결함을 왜 어떻게 무엇으로 만들었는지 알아 보는 것이 중요하겠다. 그 간결함을 쉽게 설명할 수 있다면... Angular2 Templating은 간결함의 시작중 하나라 본다. 


* 주의) 글에서 Angular 또는 Angular2는 Angular version 2를 지칭하고, AngularJS 또는 Angular1는 Angular version 1를 가르킨다. 


 

Templating 개념 둘러보기


Angular는 DOM element와 행위에 대한 것을 연관(연결) 한다. 여기서 행위(Behavior)를 Directive라고 부른다. 행위에 대한 부분이기 때문에 Directive는 CSS Selector와 맵핑되는 DOM element를 위해 인스터스화된 자바스크립이다. DOM element는 애플리케이션과 상호작용하기 위해 properties와 events를 사용하는데, Directive도 DOM element의 properties와 events의 동일 인터페이스를 사용한다. 


Angular 애플리케이션이 사용자 인터페이스는 "Component Directive"를 사용해 구성한다. Component Directive는 애플리케이션의 Data와 Logic을 저장하고, 또한 사용자 인터페이스를 정의하는 html template도 가진다. 컴포넌트 안에서 element와 상호작용하는 컴포넌트는 Decorator Directive이다. 보통 ng-show="false"와 같이 element의 attribute로 동작하고 엘러먼트에 여러개가 놓일 수 있다. 


Angular는 양방향 데이터 바인딩을 사용한다. 데이터 바인딩은 template안에 특별한 html attribute를 이용해 설정한다. 이때 바인딩은 expression이라고 부르는 것을 이용해 정의한다. expression은 함수(Function)를 호출하거나 데이터에 접근하는 것으로 모든 expression은 execution context안에서 실행된다. 이런 작용은 Dependency Injection Container 안에서 아래와 같이 수행된다.





Directive Type


지시자의 종류 목록


Provides execution context for expressions

Provides a hole in the DOM to insert template instances

Isolates the DOM/expressions/css for reuse

Decorator Directive

no

no

no

Template Directive

can create child execution context, don't have to.

yes

no

Component Directive

isolated execution context, always.

no

yes


Directive에 대한 일반 제약조건은 Directive는 DOM 구조를 제거(remove)/변경(change) 해서는 안된다. Template Directive와 Component Directvie는 별도의 Execution Context를 가질 수 있다. Angular에서 template directive가 execution context를 갖는 것에 유념하자.



Decorator Directive


새로운 element를 만들고 해당 element에서 뭐든 할 수 있다. 그러나 만들지 않은 것은 다른 element는 attribute 변경만 가능하다.



Template Directive


원래 있던 element/template 영역의 특정 부분에 template 인스턴스를 넣을 수 있고, template directive는 자식(child) execution context를 생성한다. 예로 ng-repeat는 row 마다 execution context를 만들지만 ng-if는 부모(parent) execution context를 재사용한다. Template Directive 종류로는 ng-if, ng-repeat, ng-view, ng-switch, ng-include 가 있다. 일반적인 문법을 보자 

<template ng-repeat>

  <div> ... </div>

</template>


template element 자체는 제거되고 template의 일부가 되지 않는다. 즉, template directive는 <template> element만을 허용한다. 중첩으로 아래와 같이 사용할 수도 있다. 

<template ng-repeat>

  <template ng-if>

    <div>...</div>

  </template>

</template>

    

template directives를 사용하면 element에 아래와 같이 template로 변경된다. 

<ul>

  <li ng-repeat>

    <span ng-if> ... </span>

  </li>

</ul>

은 아래 내용과 완전 동일하다

<ul>

  <template ng-repeat>

    <li>

      <template ng-if>

        <span> ... </span>

      </template>

    </li>

  </template>

</ul>


위이 template 태그는 Angular1의 directive의 compile/link 과정과 동일하다. 즉, Angular2에서는 compile/link과정을 template directive로 대체하는 것이다. 


    // Angular1의 이런 구문이 사라지는 것이다. 

    return {  

           ....

            templateUrl: 'plugins/taskers/wafer-traffic/wafer-traffic.html',

            replace: true,

            link: link,

            controller: ctrl,  

            ....

        };

    function link() {}

    function ctrl() {}



Component Directive 


javascript 로직, html template 과 옵션으로 css style을 컴포넌트에 가지고 있다. 이를 위해서 template안의 expressions을 격리(isolate)한다. - execution context의 격리: component directive 인스턴스가 template안의 expresssions를 위한 새로운 execution context가 되는 것이다. 즉, template안의 expressions은 component directive 인스턴스의 함수(function) 또는 properties만 접근 가능하다는 것이다. 이것은 Angular1의 directive 정의시 scope: {...} 격리하는 방법과 controllerAs를 사용해서 this로 접근하는 것등을 개발자가 정의할 필요없이 Component directive로 통일한 것으로 보인다. 프로젝트를 진행하다보면 거의 대부분 scope: { model: '=' } 과 controllerAs를 default로 놓고 사용하기 때문에 프레임워크 단에서 simple화 한 것은 환영할만 하다. 


  // Angular1의 이런 구문이 사라지는 것이다. 

  return {

            restrict: 'EA',

            scope: {

              model: '='

            },

            controller: trafficCtrl,

            controllerAs: 'traffic',

            bindToController: true

        };


- DOM 과 CSS의 격리: Component directives는 다른 directive에서 컨텐츠 변경을 못하도록 Shadow DOM을 사용한다. 따라서 Shadow DOM안에서의 element events는 외부 element로 전파되지 않는다. (buble out of component directive) 

   + Properties와 events: Template은 component의 properties들과 데이터 바인딩 되고, 이벤트는 상위 컴포넌트로 전파할 수 있다. 

   + CSS properties: 템플릿은 Shadow DOM을 기본으로 사용하는 컴포넌트에 한해 스타일을 변경할 수 있다. 

   + Child fragment: 템플릿은 Shadow DOM의 <content> 태그를 사용하는 템플릿을 넣는 자식 elements를 제공한다. 자식 elements의 expression은 밖의 템플릿 execution context와 계속 연결된다. 


expression을 위한 Execution Context는 클래스 인스턴스이고 이를 통해 expression에 대한 type checks등 다양한 일을 수행할 수 있다. 



Directives를 인스턴스화 하는 순서 


자식 elements전에 부모 element의 directives가 먼저 인스턴스화 하고, 만약 template directive가 존재하면 이것을 인스턴스화 하고, 다음으로 element의 decorator directive를 인스턴스화 한다. 순서는 directive 생성자의 dependency injection 순서에 의해 결정된다. 그리고 나서 최종 component directive가 인스턴스화 한다. 즉, 다음과 같다. 


>> Parent Element 

     template directive --> decorator directives --> component directive

         >> Child Elements

                template directive --> decorator directives --> component directive




templates에 데이터 바인딩 설정 방법


elements 또는 directives의 events 와 바인딩 하기


형식: @on-[event name]="[expression]" 

        예) <button on-click="doSomething()">

의미: click 이벤트가 발생하면 doSomething을 호출한다. 

DOM events를 기반으로 하는 thrid party 이벤트 시스템을 바인딩 할 수 있고, Directives에 새로운 이벤트를 정의해도 listener를 달 필요가 없다.



elements 의 properties 와 바인딩 하기


형식: @bind-[property name]="expresion" 

         예) <input bind-value="user.name">

의미: expression인 user.name에 대한 값 변경을 감시하다가 element property값을 갱신 한다. 


만일 element의 property가 바뀌었는데 expression은 writable하지 않거나, expression의 값이 바뀌었는데 property가 writable하지 않으면 에러가 발생한다. 양방향 데이터 바인딩은 directive와 element property 사이에 일어나기 때문이다. element의 attribute로 하지 않고 property로 바인딩 하는 이유는 다음과 같다. 


  - 거의 대부분의 attribute는 대응하는 property를 가진다. 만일 대응하는 property가 없으면 attribute가 대신한다. 

  - element properties는 항시 현재 값을 가진다. 그러나 attributes는 때때로 초기값을 지정해 주어야 한다. 예) <input>의 value attribute.

  - native attributes는 브라우저가 알아서 자동으로 대응하는 property 값을 바꿔준다. 

    예) <img>의 src property는 src attribute 바뀌면 자동을 변경된다)



elements의 properties 넣기 


형식: @[property name="a {{ [expression] }} b"

        예) <input title="some Text {{someValue}}">

의미: <input bind-title=" 'a ' + someValue + ' b' ">  


{{}} 를 사용하면 항상 string으로 변환하고, 단방향 연결이 된다. Angular1 directive의 @ 과 같다. 



text 넣기


형식: {{ [expression] }}

        예) hello {{user}}

의미: hello <span bind-text-content=" ' ' + user "> 


text node 내역과 데이터 바인딩도 항시 string으로 변환되고, 단방향이다. 



Guide-2 이어보기



<참조>


  - Templating 디자인 가이드 

  - Template Syntax 개발자 가이드 



posted by 윤영식