Skip to content

Latest commit

 

History

History
159 lines (104 loc) · 10.2 KB

2018-03-11-Forms.md

File metadata and controls

159 lines (104 loc) · 10.2 KB
title layout author permalink source-id published
Forms - User Input
post
kimchristian3426
/forms/
197QiLtINajnCxMtVv15k7nP2L4CFo_DA7m7PqLFYTOw
true

사용자는 링크 클릭, 버틀 클릭, 텍스트 엔터등의 DOM 이벤트들을 일으킨다. 이 페이지에서는 어떻게 컴포넌트에서 이벤트 핸들링을 앵귤러 이벤트 바인딩 문법을 사용하여 하는지 설명한다.

Run the live example / download example.

당신은 Dom 이벤트(DOM event)에 반응하여 앵귤러 이벤트 바인딩(Angular event bindings)들을 할수 있다. 많은 DOM 이벤트들을 유저 입력에 발동한다. 이러한 이벤트 바인딩은 유저의 입력을 얻는 방법이다. Dom 이벤트에 바인딩 하기 위해서. 괄호 속에 이벤트명을 둘러싸고 템플릿 선언으로 이것을 할당한다. 아래에 클릭 핸들러를 구현한 이벤트 바인딩을 보여주고 있다.

<button (click)="onClickMe()">Click me!</button>

이벤트 객체 타입핑은 전체 전체 돔의 이벤트가 메소드로 통과할때 아주 중요한 사항을 밝혀낸다: 컴포넌트는 너무 많은 템플릿에 상세함에 대한 자각을 가진다. 이것은 HTML 구현에 대한 것을 알아야 하는 것 없이는 정보를 추출할수 없다. 이것은 템플릿과 컴포넌트 사이의 관심사 분리를 깨지게 한다.

그 다음은 섹션에서는 이 문제에 대해서 템플릿 레퍼런스 변수들을 사용하는 것을 보여준다.

@Component({
  selector: 'app-loop-back',
  template: `
    <input #box (keyup)="0">
    <p>{{box.value}}</p>
  `
})
export class LoopbackComponent { }

The template reference variable named box, declared on the element, refers to the element itself. The code uses the box variable to get the input element's value and display it with interpolation between

tags. 엘리멘트에 선언된 box로 네이밍한 템플릿 레퍼런스 변수는 , 엘리멘트 자체를 참조한다. 코드에서 box 변수는 input 변수의 값을 얻기 위해서 사용되고

태그들 사이에 interpolation으로 나타낸다.

The template is completely self contained. It doesn't bind to the component, and the component does nothing. 템플릿은 자체로 포험되었다. 이것은 컴포넌트에 바인드 되지않았고 컴포넌트는 아무것도 하지 않았다.

Type something in the input box, and watch the display update with each keystroke.

유저 데이터를 얻는 다른 방법이 있다: 사용하라 앵귤러 템플릿 레퍼런스 변수를. 템플릿 레퍼런스 변수는 템플릿 이내에 있는 엘리멘트에 직접적인 엑세스를 제공한다. 템플릿 레퍼런스 변수를 선언하기 위해서 해시 문자열을 가진 인식자로 한다.

다음 예는 간단한 템플릿 안에서 키스크로크 루프백을 구현한 템플릿 변수를 사용한 예이다.

<input #box (keyup)="0">
<p>{{box.value}}</p>

It's easier to get to the input box with the template reference variable than to go through the $eventobject. Here's a rewrite of the previous keyup example that uses a template reference variable to get the user's input. $event 객체를 통해서 보다 , 템플릿 레퍼런스 변수를 가진 input box 를 얻는것이 더 쉽다. 여기 템플릿 레퍼런스 변수로 사용자의 입력을 얻는 방법이 사용된 KeyUp 이전 예제를 다시 작성했다.

@[Component](https://angular.io/api/core/Component)({
 selector: 'app-key-up2',
 template: `
 <input #box (keyup)="onKey(box.value)">
  <p>{{values}}</p>
  		`
})
export class KeyUpComponent_v2 {
values = '';
  onKey(value: string) {
this.values += value + ' | ';
  }
}

A nice aspect of this approach is that the component gets clean data values from the view. It no longer requires knowledge of the $event and its structure.

이러한 좋은 접근은 컴포넌트가 view 로부터 깨끗한 데이터들을 가져온다. 이것은 $event 그리고 이 구조에 대한 지식은 더이상 필요로 하지 않는다.

The (keyup) event handler hears every keystroke. Sometimes only the Enter key matters, because it signals that the user has finished typing. One way to reduce the noise would be to examine every $event.keyCode and take action only when the key is Enter.

keyup 이벤트 핸들러는 모든 키입력을 듣는다. 가끔 유저가 타이핑을 끝냈다고 하는 신호이기 때문에 중요하다. 소음을 줄이는 한 방법은 키가 엔터키 일때 동작을 취하거나 모든 $event.keyCode 를 검사하는 것이다.

There's an easier way: bind to Angular's keyup.enter pseudo-event. Then Angular calls the event handler only when the user presses Enter.

여기에는 쉬운 방법이 있다. 앵귤러의 keyup.enter 의 가짜 이벤트를 바인드 한다. 그리고 나서 앵귤러 유저가 엔터를 입력할때만 이벤트 핸들러를 호출한다.

@Component({
  selector: 'app-loop-back',
  template: `
    <input #box (keyup)="0">
    <p>{{box.value}}</p>
  `
})
export class LoopbackComponent { }

In the previous example, the current state of the input box is lost if the user mouses away and clicks elsewhere on the page without first pressing Enter. The component's value property is updated only when the user presses Enter.

To fix this issue, listen to both the Enter key and the blur event.

이전 예시에서 input box 의 현재의 상태는 만약에 유저가 마우스를 벗어나거나 엔터 키 없이 페이지를 클릭한 상태라면 데이터를 소실할수 있다. 컴포넌트의 value 속성은 유저가 엔터키를 누룰때마다 업데이가 일어난다. 이러한 이슈를 바로잡기 위해서, 엔터키, blur 이벤를 각각 리스닝한다.

@Component({ selector: 'app-key-up4', template: ` <input #box (keyup.enter)="update(box.value)" (blur)="update(box.value)">

<p>{{value}}</p>

` }) export class KeyUpComponent_v4 { value = ''; update(value: string) { this.value = value; } }

The previous page showed how to display data. This page demonstrated event binding techniques.

Now, put it all together in a micro-app that can display a list of heroes and add new heroes to the list. The user can add a hero by typing the hero's name in the input box and clicking Add.

이전 페이지는 어떻게 데이터를 보여주는 지를 알아보았다. 이 페이지는 이벤트 바인딩 기술들을 설명하려고한다.

현재, heroes의 목록과 새로운 히어로즈를 추가하는 마이크로 앱을 함께 놓았다. 유저는 heroe의 이름을 입력 박스에 타이핑하여 추가 할수 있고 클릭하여 추가한다.

  • Use template variables to refer to elements — The newHero template variable refers to the element. You can reference newHero from any sibling or child of the element. 엘리멘트들을 참조하기 위해서 template variables 를 사용하라 - newHero template variable은 input 엘리멘트를 참조한다. 당신은 엘리멘트의 형제 , 또는 자식로부터 새로운 newHero 를 참조할수 있다.

  • Pass values, not elements — Instead of passing the newHero into the component's addHero method, get the input box value and pass that to addHero. 엘리멘트가 아닌 값을 통과시켜라.- 컴포넌트의 addHero 메서드로부터 newHero로를 통과 시키는 것 대신에 input box 로부터 값을 얻어오고 addHero로 통과시켜라

  • Keep template statements simple — The (blur) event is bound to two JavaScript statements. The first statement calls addHero. The second statement, newHero.value='', clears the input box after a new hero is added to the list. template statements을 간단하게 유지하라 - blur 이벤트는 두개의 자바스크립트 선언을 바인드 한것이다.첫번쨰 선언은 addHero 를 호출했다. 두번째 선언은 newHero.value='' 은 새로운 hero 입력후에 입력 박스를 초기화했다.

You have mastered the basic primitives for responding to user input and gestures.

These techniques are useful for small-scale demonstrations, but they quickly become verbose and clumsy when handling large amounts of user input. Two-way data binding is a more elegant and compact way to move values between data entry fields and model properties. The next page, Forms, explains how to write two-way bindings with NgModel.