티스토리 뷰
반응형
이벤트로 값을 전달 하는 법
input 태그를 사용하여 설명한다.
<input type="text" (input)="showName()">
이런 코드 가 있다.
input 이란 이벤트가 발생 할 때 마다 showName 이란 함수를 실행하라는 말이다.
그러면 Component 코드를 보자
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
name;
constructor() {
}
ngOnInit() {
}
showName() {
console.log('hi');
}
}
이런코드가 있다.
input 란에 아무 글짜나 입력하면 계속해서 hi가 콘솔에 찍히는 걸 볼 수 있다...
그러면 input 으로 입력하는 값을 콘솔로 찍고 싶다면 어떻게 해야 할까?
$event 라는 예약된 변수를 사용한다. click과 input은 dom에 내장된 이벤트인데 이 이벤트들의 경우 이벤트와 함께
데이터를 전달한다. 그리고 이러한 이벤트는 예약변수인 $event로 받을 수 있다.
<input type="text" (input)="showName($event)">
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
name;
constructor() {
}
ngOnInit() {
}
showName(eventVariable: Event) {
console.log(eventVariable)
}
}
입력시 이런식으로 이벤트가 출력되는 걸 확인할 수 있다.
그리고 target.value 값에 현재 입력한 값이 들어간 걸 볼 수 있다.
그럼 코드를 수정해 보자
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
name;
constructor() {
}
ngOnInit() {
}
showName(eventVariable: Event) {
this.name = eventVariable.target.name;
console.log(this.name);
}
}
이런식으로 수정후 input에 값을 입력하면 자신이 입력한 값만 잘 출력 되는 것을 확인 할 수 있다.
그런데 이런식으로 빨간 줄이 표시되는 걸 볼 수 있다. 물론 출력은 되지만 앵귤러가 기본적으로 TS이기 때문에 타입을 명시해 줘야 한다.
이런식으로 event target의 타입을 명시해 주어야 한다. 둘다 똑같긴 한데 밑에 것이 최신이다.
이걸 응용하면
<input type="text" (input)="showName($event)">
{{name}}
이런식으로 사용 할 수도 있다.
'Angular8' 카테고리의 다른 글
[Angular] ngIf structure directive 구조 디렉티브 (0) | 2020.04.07 |
---|---|
[Angular] 양방향 바인딩 Two-Way-DataBinding (0) | 2020.04.07 |
[Angular] Event Binding 1 이벤트 바인딩 (0) | 2020.04.07 |
[Angular] Data binding 1 (0) | 2020.04.07 |
[Angular] String Interpolation (0) | 2020.04.07 |