Angular 5 binding material 5 DatePicker to form fi

2019-08-22 12:03发布

I am trying to bind an Angular materials 5 date picker to a form field, i am following the official tutorial here but there isn't any information about how to bind the calendar value to a field within a form, it could also be bound to a class attribute, but that also does not work. My template is simply:

 <form #theForm="ngForm">
   .......Some fields.......
   <mat-form-field>
                  <input matInput [matDatepicker]="fixDate" placeholder="Choose a date" name="fixDate">
                  <mat-datepicker-toggle matSuffix [for]="fixDate"></mat-datepicker-toggle>
                  <mat-datepicker #fixDate></mat-datepicker>
              </mat-form-field>
 </form>

So this piece of template within the <mat-form-field> tags, consists of an input within a form, by giving it a name, i would expect it to be 'catchable' from the .ts, but it does not work, what i do in the .ts file is:
(click)="saveReport(theForm)"

`public saveReport(form: NgForm){
    if(confirm("Sure you wanna save?")){
      //Some non relevant validation
      let valuesFromForm = form.value;
      console.log(valuesFromForm['fixDate']);
    }
}`

This prints undefined, but other fields in the form work just fine, when you give them a name they are retrievable via the form object in the .ts file Any advise?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-22 12:17

Using reactive forms the following works for me using mat-datepicker.

My xxx.component.html file looks for example like follows. (Very similar to yours accept the reactive forms bindings)

<form [formGroup]="myForm" (ngSubmit)="save(myForm.value)">
  <mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Start" formControlName="date">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>
  <button mat-raised-button color="accent" [disabled]="myForm.invalid">Save</button>
</form>

in the xxx.component.ts I import the reactive forms related targets FormBuilder, FormGroup, FormControl. And Validators if you want to validate. Then

myForm: FormGroup;

constructor (private fb: FormBuilder) {
  this.myForm = fb.group({
    date: ['', Validators.required]
  });
}

[...]

save(data: YourDataType) {
  /* Here you go */
}

Now you should be able to grab data.date as your selected value not beeing undefined. At least it can be an empty string, which you can prevent by adding validators. Of course you have to import the MatFormFieldModule and MatDatepickerModule from @angular/material and import it in your component related module.

Hope this answers your question properly and helps for solving your problem. Cheers!

查看更多
登录 后发表回答