728x90

JavaScript와 HTML, CSS등에 대해서는 일체 다루지 않는다.

기초지식은 다른 강의를 참조하도록 하라.

또한 Angular에서는 JavaScript로 번역되는 TypeScirpt라는 새로운 언어를 사용한다.

이 언어는 JavaScript에 Type을 추가한 언어로 좀더 객체지향적인 설계가 가능한 언어이다.

이 언어에 대해서 조금씩의 설명은 있겠지만 자세한 설명은 다루지 않을 계획이다.

필자는 아직 이 TypeScript를 강의로 제공할 생각이 없으므로 자세히 알고싶다면

https://www.typescriptlang.org/

를 참조하라.


이 때까지 template에 변수 바인딩을 하는 예제를 수도 없이 보았다.

이제 어떻게 제대로 사용하는지에 대해서 알아보도록 하자.


1.interpolation

2.property bind

3.on bind(event bind)

4.class bind

5.style bind(css bind)


Interpolation


<p>{{name}}</p>

가장 기초적인 바인딩이다.


Property Bind


import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myUrl = 'https://www.naver.com';
}

html내의 프로퍼티를 바운딩하려면 어떻게 해야할까?

위의 myUrl을 바운딩 해보도록 하자.


<a href="{{myUrl}}">my page</a><br>
<a [href]="myUrl">my page</a><br>

일반적인 방법으로 Interpolation을 사용하는 방법이 있다.

그러나 일반적으로 이렇게 사용하지 않고 PropertyBind를 사용한다.

이것은 그 프로퍼티를 []괄호로 감싸주면 된다.


On Bind(Event Bind)


import {Component} from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
showName = function (name: string) {
alert(name);
};
showAge = (age: number) => alert(age);
}

해당 클래스에 showName과 showAge라는 메소드를 선언해준다.

그러면 이 메소드 역시 html렌더링 할때 넘어가게 되므로 변수로서 사용할 수 있다.


<button (click)="showName('kukaro')">click!</button>
<button (dblclick)="showAge(26)">double click!</button>

이벤트를 바운딩 할때는 ()괄호로 감싸주면된다.


제대로 작동하는 것을 확인할 수 있다.


Class Bind

import {Component} from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isSpecial = true;
}
<div [class.special]="!isSpecial">hi</div>
<div [class.special]="isSpecial">hello</div>

위의 코드를 보면 해당 div에 해당 class special값이 생기냐 안생기냐가 정해진다.

예를 들면 위의 경우에는 false이므로 special클래스가 존재치 않게 되고,

아래의 경우에는 true이므로 special클래스가 존재하게 된다.


Style Bind(css Bind)


import {Component} from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myColor = 'red';
myFontSize = 15;
myBackColor = 'green';
}

보면 css로 넘겨줄 값들을 각각 정해주었다.

html에서 받으려면 아래처럼 사용하여야 한다.


<div [style.color]="myColor" [style.font-size]="myFontSize" [style.background-color]="myBackColor" >hello</div>

class할 때 처럼 사용하면 된다.



제대로 작동하는것을 확인하자.



'Programming > TypeScript-Angular' 카테고리의 다른 글

[Angular-09]angular directive  (0) 2018.04.25
[Angular-08]angular module(component 및 module 만들기)  (0) 2018.04.22
[Angular-06]if문  (0) 2018.04.22
[Angular-05]for문  (0) 2018.04.22
[Angular-04]angular component  (0) 2018.04.22

+ Recent posts