프로젝트 생성 및 실행
1 2 3 4 5 |
# toh라는 프로젝트 생성 ng new toh # 해당 폴더로 이동후 4200번 포트로 띄우고 실행한다. cd toh ng serve --port 4200 --open |
새로운 컴포넌트 추가
heroes 컴포넌트 만들기
1 |
ng g component heroes |
app.component에 연결하기
1 |
<app-heroes></app-heroes> |
화면에 heroes works 가 보일것이다.
바인딩 – interpolation
heroes.component.ts에 property 추가
1 |
hero = 'Winstorm'; |
template에 바인딩
1 2 3 |
<p> {{hero}} </p> |
컴포넌트란 무엇인가?
vue, react, angular에 공통된 사항중 하나가 컴포넌트 개발 방식이다. 기존 jquery같은 경우는 view만 가지고 있고 모델(데이터, 변수) 정보를 갖고 있지 않다. 그래서 data-xxx=”aaa” 이런식으로 attribute에 모델 정보를 넣어서 처리하고 했다. 하지만 컴포넌트는 view 뿐만 아니라 모델 정보를 가질수 있으며, 기본적으로 모델 정보를 가지고 이것을 view에 보여주는데 이것을 바인딩이라 한다.
html 문서가 view와 자바스크립트, css를 모두 가지고 있는것과 동일하게 컴포넌트도 view요소인 html 템플릿, 자바스크립트 영역, css 영역을 모두 가지고 있는 아주 작은 html 덩이리, 부품이라고 할수 있다. 그리고 jquery 처럼 view를 직접 조작하는게 아니라 model 정보를 가지고 view를 표현하는 방식 (이것을 바인딩이라 한다)을 통해서 좀 더 쉽게 화면을 다룰수 있게 된다. 그래서 컴포넌트를 MVVM 혹은 MVC 등으로 부른다.
바인딩 – interpolation(객체)
회원정보 등 보통 객체가 여러가지의 속성값을 갖게 되는 경우가 흔한 경우이다. hero 객체를 만들고 객체를 바인딩해보자.
1 2 3 4 |
export class Hero { id: number; name: string; } |
화일명은 kebob-case로 객체 이름은 camel-case로 사용한다.
class 는 es6에 새롭게 만들어진 객체를 정의하는 방법이다. typescript에서 타입을 정의하는 방법은 변수명 다음에 콜론(:) 다음에 타입명을 명시한다. 객체를 생성하는 방법은 생성자 함수를 이용하는 방법과 리터럴 객체를 이용하는 방법 두가지가 있다.
1 2 3 4 5 6 7 8 9 10 11 |
export class HeroesComponent implements OnInit { hero: Hero = { id: 1, name: 'Windstorm' }; constructor() { } ngOnInit() { } } |
템플릿에서 모델의 객체를 이용하여 바인딩한다.
1 2 3 |
<h2>{{ hero.name }} Details</h2> <div><span>id: </span>{{hero.id}}</div> <div><span>name: </span>{{hero.name}}</div> |
바인딩 – property 바인딩
model -> view 로의 바인딩하는 property 바인딩을 알아보자. property 바인딩에는 attrbute 바인딩, class 바인딩, style 바인딩 크게 세가지가 있다. 각각 살펴보자.
1 2 3 4 5 6 7 8 9 10 11 |
<div> <button [disabled]="isSpecial">propery binding button</button> </div> <div> <div [class.special]="isSpecial">class binding button</div> </div> <div> <button [style.color]="isSpecial ? 'red' : 'green'">style binding button</button> </div> |
property 바인딩을 하게되면 오른쪽은 angular context 영역이 된다. 그러므로 isSpecial을 angular context에 변수 선언을 해줘야 한다.
class 바인딩을 하게 되면 오른편이 true일때 [class.property] 이 부분이 class=”property” 로 렌더링 된다. 즉, class=”special”
style 바인딩은 오른쪽이 true 일때 style=”color: red” 로 바인딩된다.
1 |
isSpecial = true; |
1 2 3 |
.special { background-color: blue; } |
바인딩 – event 바인딩
event 바인딩은 model -> view로의 바인딩이 아니라 반대방향이다 view에서 model로 바인딩한다.
1 2 3 |
<div> <button (click)="onSave($event)">event binding save button</button> </div> |
1 2 3 |
onSave(event: any) { console.log(event); } |
바인딩 – two way binding
input 박스를 만들고 input 박스를 수정하면 즉, view단을 수정하면 model 을 변경하고 ( view -> model)
변경된 model 정보는 다시 {{ }} 로 바인딩된 view를 수정하게된다. [ ] 은 model -> view 바인딩이고 ( ) 는 view -> model의 바인딩을 가르킨다.
1 2 3 4 5 |
<div> <label>name: <input [(ngModel)]="hero.name" placeholder="name"> </label> </div> |