Why am I getting an undefined value when I try to check my Input?


#1

Hey guys, I’m trying to get the value of my Input as a string but It’s undefined

<form class="mylist">
      <ion-item>
        <ion-label>Start:</ion-label>
        <ion-input value="" [(ngModel)]="start" id="start" [ngModelOptions]="{standalone: true}"></ion-input>
      </ion-item>
  </form>
declare var start: string;
...
start = (<HTMLInputElement>document.getElementById('start')).value;
      console.log(start);

I hope someone can help me out


#2

Uhhh, where is that piece of script located? I haven’t seen it done that way before, you should do it like this, in the component class for the html

class MyComponent {
    private start;
    
    someAction() {
        console.log(start);
    }
}

Or is there a specific reason you’re doing it that way?


#3

You’re binding start to an element which probably isn’t created at this point. Please make sure it’s in the dom before binding/logging it like this. So @mich356c gives you a good pointer. BTW I think it’s bad design to use document.getElementById with Angular2. Please use @ViewChild whenever you can since it’s platform agnostic.


#4

yes, I need this to calculate and display a route in google maps

calculateAndDisplayRoute() { 
      start = (<HTMLInputElement>document.getElementById('start')).value;
      console.log(start);
      this.directionsService.route({
          origin: String(start),
          destination: end,
          travelMode: 'DRIVING'
      }, (response, status) => {
          if (status === 'OK') {
              this.directionsDisplay.setDirections(response);
          } else {
              window.alert('Directions request failed due to ' + status);
          }
      });
  }

thanks for help


#5

Did you try what I recommended?


#6

I think you don’t really understand the scope of Angular2 here. Why use ngModel if you’re going to use document.getElementById to read the value of start?