본문 바로가기

WEB

Angular - template reference variable (#)

참고문서: https://itnext.io/working-with-angular-5-template-reference-variable-e5aa59fb9af

 

아래 그림과 같이 앵귤러 html 템플릿에서 html 요소에 #을 이용해서 레퍼런스를 지정해 줄 수 있다. 

<input type="text" #firstNameInput>
<input type="text" #lastNameInput>

 

레퍼런스를 지정해 주면 템플릿이나 컴포넌트 내에서 자유롭게 참조하여 사용할 수 있다. 

아래 그림과 같이 click 이벤트 발생시 함수에 레퍼런스를 전달할 수 있다. 

<button (click)="show(lastNameInput)">Show</button>

 

함수내에서 인자로 전달 받을 다음과 같이 받을 있다. 

show(lastName: HTMLInputElement){
    console.log(lastName.value);
}

 

전달 받는 인자는 HTMLInputElement 타입이 된다. 

 

컴포넌트 내에 다음과 같이 선언하여 활용 할 수 있다. @ViewChild 데코레이션을 활용하면 된다. 

import {ViewChild, ElementRef} from '@angular/core';
// Reference firstNameInput variable inside Component
@ViewChild('firstNameInput') nameInputRef: ElementRef;

 

'WEB' 카테고리의 다른 글

앵귤러 브라우저 체크 라이브러리  (0) 2020.01.27
jquery text  (0) 2011.05.28
팝업창 띄우는 법  (0) 2011.05.28