angular2 - reference <input> template reference variable in component to change value property

3.5k Views Asked by At

How do I access the value property of an element in the component in Angular2?

In the Template:

<input #myInput (keyup.enter)="onInput(myInput)"/> 

In the Component code:

import {ElementRef} from '@angular/core';
...
onInput(latLngInputElement: ElementRef) {
  // I want to access the value property of the <input> element here, and
  // modify it so that it is reflected back in the template.

I know that I can pass the myInput.value into the code, but I need the reference so that I can also use the function to update the .value property of the element.

I'd like to know if there is a way to do this that does not involve two way binding to a global variable, because I think it is cleaner to have as few globals as possible. Thanks!

1

There are 1 best solutions below

6
On

Angular's solution to this would be two-way binding of the input model to a variable in the component. This wouldn't involve dirtying up the global scope, expecially if you declare the var with a let as per Typescript's docs.

I'd like to know if there is a way to do this that does not involve two way binding to a global variable, because I think it is cleaner to have as few globals as possible. Thanks!

I understand this, but invoking ElementRef might be the worse of two evils here. The Angular docs greatly discourage using it as Angular already does so much to handle the DOM API.

However, you should be able to get the value from latLngInputElement.value.

If you're looking for a cleaner solution:

I would highly recommend checking out Angular's FormBuilder to build a model-driven form as opposed to a template-driven one. It's a very elegant way to control form values on a page programatically instead of on the template. Scotch.io has an excellent blog post on it. It's well worth learning.

Good luck!