0

I have a datepicker in a form of my html file. After submitting the form I need to get the selected value of the datepicker in my component.ts file

in the html file:

<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<input type="text" class="datepicker" ngModel id ="from" name="from" placeholder="From :"> 
</form>

in the component.ts file:
console.log(f.value.from); 

I have tried the above code and the value I get is undefined.

Dinz_N
  • 23
  • 1
  • 2
  • 9

2 Answers2

0

Add [(ngModel)]

<input type="text" class="datepicker" [(ngModel)]="from" id ="from" name="from" placeholder="From:">

And in .ts declare

public from;

then it should be avaliable in onSubmit function

Paweł Rymsza
  • 411
  • 3
  • 9
0

See this stackblitz

https://stackblitz.com/edit/angular-dcr7ub

Note the two way binding in the form [(ngModel)]="date" links to date in app.component.ts though you could do this using reactive forms.

app.component.html

<form (ngSubmit)="onSubmit()" #f="ngForm">
  <div class="example-container">
  Form
    <mat-form-field>
      <input matInput [(ngModel)]="date" [matDatepicker]="picker" name="date" placeholder="Choose a date" />
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
      </mat-form-field>
 </div>

  <button type="submit" class="btn btn-success">Submit</button>
</form>

There are a few tricky things I encountered implementing this:

import {MatDatepickerModule} from '@angular/material/datepicker';
import {MatFormFieldModule, MatInputModule} from '@angular/material';
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import { MatMomentDateModule } from "@angular/material-moment-adapter";

The last one being as you have to provide a DateAdapter for dealing with dates (the datepicker is agnostic about this).

  • Remember to include a theme in styles.css, I used:
@import '@angular/material/prebuilt-themes/deeppurple-amber.css';

So in my example the date is a moment (https://momentjs.com/) object hence the .format() in:

  onSubmit() {
    console.log((<any>this.date).format());
  }
Andrew Allen
  • 6,512
  • 5
  • 30
  • 73