santhosh
santhosh

Reputation: 435

ngModel value is coming as undefined when used with input

html:

    <input [(ngModel)]="timestamp">
    <button (click)="getInstantDetails()">display</button>

component.ts

  timestamp: any;
  getInstantDetails(): void {
    console.log(this.timestamp);
}

app.module.ts

import {FormsModule} from '@angular/forms';
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        FormsModule,
      ],
      providers: [SchedulerService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

I'm getting timestamp value as undefined. is there anything I'm missing here.?

Upvotes: 0

Views: 9386

Answers (2)

Chris Barr
Chris Barr

Reputation: 33962

Don't use timestamp: any; - this is identical to timestamp: any = undefined; since you are not setting a value, the initial value is undefined.

Avoid using any as well, this means "I have absolutely no idea what this variable could be". Since you are using it for an input, it's probably going to be a string.

Just do this instead: timestamp = ''; - this defines it as a string and give it an initial starting value as an empty string, which is probably what you are expecting

Upvotes: 0

Tomasz Kula
Tomasz Kula

Reputation: 16837

Everything is working as expected. You did not initialize timestamp: any to anything so its undefined.

Change timestamp: string = 'hello'; and getInstantDetails() will log 'hello'.

Live demo

Upvotes: 2

Related Questions