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

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

1 Like

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?

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.

1 Like

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

Did you try what I recommended?

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?