티스토리 뷰
반응형
우선 양방향 바인딩을 하기 위해서는 주의할 점이 있다.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
이런식으로 imports 부분에 FormsModule을 추가해 주어야 한다.
이제 실제 코드를 살펴보자
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
name;
constructor() {
}
ngOnInit() {
}
changeName(event: Event) {
this.name = (event.target as HTMLInputElement).value;
}
}
<input type="text" [(ngModel)]="name"><br>
<input type="text" (input)="changeName($event)"><br>
{{name}}
양방향 바인딩 예제이다.
두인풋 창을 모두 입력 해 보면 양방향 바인딩과 아닌 것의 차이를 알 수 있다.
[(ngModel)]을 사용한 것이 양방향 바인딩이다.
1. 천번째 인풋에 입력을 해본다.
양방향 바인딩이므로 name에 인풋의 value가 바인딩 되어 {{name}} 을 통해 화면에 출력된다.
그러나 두번째 인풋은 변화가 없다.
2. 두번째 인풋에 입력을 해본다.
이벤트 바인딩에서 한 것과 같다. 화면에 그대로 출력된다. 그러나 1번에서 한 것과 다르게 이번에는 첫번째
인풋에도 그대로 나타난다.
즉 ngModel은
컴포넌트 <-> 템플릿 간에 모두 동시에 바인딩 된 것.
템플릿의 변화가 있던 컴포넌트 코드에 변화가 있던 양방향 바인딩은 모두 적용 되지만
단방향인 event 의 경우 TS코드의 값이 변했다고 해도 템플릿에서 보여지는 값은 그대로 이다.
'Angular8' 카테고리의 다른 글
[Angular] ngStyle 동적으로 css 변경하기 (0) | 2020.04.07 |
---|---|
[Angular] ngIf structure directive 구조 디렉티브 (0) | 2020.04.07 |
[Angular] Event Binding 2 (0) | 2020.04.07 |
[Angular] Event Binding 1 이벤트 바인딩 (0) | 2020.04.07 |
[Angular] Data binding 1 (0) | 2020.04.07 |