앵귤러의 데이터바인딩은 두가지 종류가 있습니다
단방향바인딩과 양방향 바인딩
단방향 바인딩은 컴포넌트에서 뷰로 뷰에서 컴포넌트로 한방향으로만 바인딩 해주는기능입니다
양방향 바인딩은 컴포넌트 < - >뷰 정보가 바뀌면 자동으로 바인딩 해주는 기능입니다
바인딩 실습을위한 컴포넌트를 만들어줍니다
명령프롬프트 ng g c bind/oneway
명령프롬프트 ng g c bind/twoway
※ng g c bind/oneway는 bind폴더를 만들고 그밑에 oneway 컴포넌트를 만들라는것입니다
디렉터리 구조는 이렇습니다
컴포넌트를 라우팅에 추가해줍니다
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {DemoComponent} from './demo/demo.component';
import {Demo2Component} from './demo2/demo2.component';
import {OnewayComponent} from './bind/oneway/oneway.component';
import {TwowayComponent} from './bind/twoway/twoway.component';
const routes: Routes = [
{path: 'demo', component: DemoComponent},
{path: 'demo2', component: Demo2Component},
{path: 'oneway', component: OnewayComponent},
{path: 'twoway', component: TwowayComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
그리고 앱컴포넌트 사이드바에 메뉴도 추가해줍니다
app.component.ts
import { Component } from '@angular/core';
import {NbMenuItem} from '@nebular/theme';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'my-app';
items = [
{
title: 'demo',
link: ['demo'],
},
{
title: 'demo2',
link: ['demo2'],
},
{
title: 'Binding',
expanded: true,
children: [
{
title: 'One-way',
link: ['oneway'],
},
{
title: 'Two-way',
link: ['twoway'],
},
],
},
];
}
먼저 단방향 바인딩입니다
Interpolation 인터폴레이션: 컴포넌트에 정의한 변수를 템플릿에서 사용합니다
사용법 {{ variable }}
Property binding 프로퍼티바인딩: 엘리먼트의 프로퍼티를 []를사용해 바인딩합니다
사용법 <input [value]="variable">
Event binding 이벤트바인딩: 엘리먼트의 핸들러로 컴포넌트의 메소드를 바인딩합니다
사용법 <button (click)="say()">
간단하게 종류와 사용법을알아 봤습니다 실제코드는 이렇습니다
oneway.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-oneway',
templateUrl: './oneway.component.html',
styleUrls: ['./oneway.component.scss']
})
export class OnewayComponent implements OnInit {
i: number = 1;
str: string = 'Hello';
flag: boolean = true;
constructor() { }
ngOnInit() {
}
say(): string {
return 'Hi';
}
clickBind(): void {
alert('클릭 바인딩');
}
}
oneway.component.html
<nb-card>
<nb-card-body>
클래스 변수 i: {{ i }}<br>
산술: {{ 1+2 }}<br>
클래스 변수 str: {{ str }}<br>
메소드 say(): {{ say() }}<br>
<br>
<input [disabled]="flag"><br>
<input [disabled]="!flag"><br>
<input [value]="say()"><br>
<button (click)="clickBind()">event</button>
</nb-card-body>
</nb-card>
그리고 nb-card 태그를 쓰기위해서 앱모듈 imports에 NbCardModule을 추가해줍니다
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DemoComponent } from './demo/demo.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {NbThemeModule, NbLayoutModule, NbSidebarModule, NbMenuModule, NbCardModule} from '@nebular/theme';
import { Demo2Component } from './demo2/demo2.component';
import { OnewayComponent } from './bind/oneway/oneway.component';
import { TwowayComponent } from './bind/twoway/twoway.component';
@NgModule({
declarations: [
AppComponent,
DemoComponent,
Demo2Component,
OnewayComponent,
TwowayComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
NbThemeModule.forRoot({ name: 'default' }),
NbLayoutModule,
NbSidebarModule.forRoot(),
NbMenuModule.forRoot(),
NbCardModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
그리고 브라우저를통해 확인을해보면
{{ i }} 가 컴포넌트에정의한 i = 1 이들어간것을확인할수있습니다
2줄에서는 변수를 사용하지않고 간단한산술을하였습니다
{{ }} 인터폴레이션에 적은것은 자바스크립트코드가 되기때문에 산술된결과를얻을수있습니다
문자열도 출력되구요
4줄 say() 메소드의 리턴값이 출력됩니다
여기까지 인터폴레이션을 사용했습니다
input 태그에 [disabled]="flag" 변수flag의 값을통해 disabled 처리되었고
프로퍼티바인딩도 자바스크립트코드가되기때문에 !flag를하면 disabled=false 가됩니다
마지막으로 이벤트바인딩입니다
버튼에 (click)="clickBind()" 버튼태그에 (click)으로 엘리먼트를 클릭했을때 clickBind()메소드가 동작하게됩니다
------------------------------------------------------------------------------------------------------------------------------------------------------
양방향 바인딩을 사용하기위해선 모듈에 FormsModule이 추가되있어야합니다
@angular/forms 에 있으므로 따로설치하지않고 앱모듈에 추가해줍니다
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DemoComponent } from './demo/demo.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {NbThemeModule, NbLayoutModule, NbSidebarModule, NbMenuModule, NbCardModule} from '@nebular/theme';
import { Demo2Component } from './demo2/demo2.component';
import { OnewayComponent } from './bind/oneway/oneway.component';
import { TwowayComponent } from './bind/twoway/twoway.component';
import {FormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
DemoComponent,
Demo2Component,
OnewayComponent,
TwowayComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
NbThemeModule.forRoot({ name: 'default' }),
NbLayoutModule,
NbSidebarModule.forRoot(),
NbMenuModule.forRoot(),
NbCardModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
글맨위에
양방향 바인딩은 컴포넌트 < - >뷰 정보가 바뀌면 자동으로 바인딩 해주는 기능이라고 설명했습니다
사용법은 엘리먼트 태그에 [(ngModel)]="바인딩대상" 으로 사용합니다
코드를 보겠습니다
twoway.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-twoway',
templateUrl: './twoway.component.html',
styleUrls: ['./twoway.component.scss']
})
export class TwowayComponent implements OnInit {
value: string = 'Hi';
selectVal: string = 'one';
checkVal: boolean = false;
constructor() { }
ngOnInit() {
}
}
twoway.component.html
<nb-card>
<nb-card-body>
<input [(ngModel)]="value"><br>
실시간 value 값: {{ value }}
<br><br>
<select [(ngModel)]="selectVal">
<option *ngFor="let item of ['one','two','three','four']">
{{ item }}
</option>
</select><br>
실시간 selectVal 값: {{ selectVal }}
<br><br>
<input type="checkbox" [(ngModel)]="checkVal"> 체크밸류<br>
실시간 checkVal 값: {{ checkVal }}
</nb-card-body>
</nb-card>
※ option 태그에 *ngFor라는게 보입니다 directive 디렉티브라고 하는데 다음포스트에서 설명합니다
브라우저로 확인해보면
영문일 경우는 문제없이 잘 수행되지만 한글일 경우는 약간의 문제가 있습니다 바로바로 화면에 적용되지 않는 것이죠
영문과 다르게 한글은 조합형 문자이기 때문에 글자가 다 만들어 지기 전까지는 화면에 출력되지 않게 되는 것입니다
문제를 해결하기위해 COMPOSITION_BUFFER_MODE 설정을 변경하셔야합니다
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DemoComponent } from './demo/demo.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {NbThemeModule, NbLayoutModule, NbSidebarModule, NbMenuModule, NbCardModule} from '@nebular/theme';
import { Demo2Component } from './demo2/demo2.component';
import { OnewayComponent } from './bind/oneway/oneway.component';
import { TwowayComponent } from './bind/twoway/twoway.component';
import {COMPOSITION_BUFFER_MODE, FormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
DemoComponent,
Demo2Component,
OnewayComponent,
TwowayComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
NbThemeModule.forRoot({ name: 'default' }),
NbLayoutModule,
NbSidebarModule.forRoot(),
NbMenuModule.forRoot(),
NbCardModule,
FormsModule
],
providers: [
{
provide: COMPOSITION_BUFFER_MODE,
useValue: false
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
다시브라우저를통해 확인해보면
입력하는대로 바인딩되는것을 확인할수있습니다
'DEV > Angular' 카테고리의 다른 글
Angular 앵귤러 배우기 - 7 디렉티브 Directive (0) | 2018.12.28 |
---|---|
Angular 앵귤러 배우기 - 5 라우팅 Routing (0) | 2018.12.24 |
Angular 앵귤러 배우기 - 4 네뷸라모듈설치 NebularModule (0) | 2018.12.24 |
Angular 앵귤러 배우기 - 3 컴포넌트 Component (0) | 2018.12.24 |
Angular 앵귤러 ngx-admin 관리자 키트 (0) | 2018.11.08 |