Angular 5 binding material 5 DatePicker to form field

China☆狼群 提交于 2019-12-11 18:54:18

问题


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:


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!



来源:https://stackoverflow.com/questions/48744431/angular-5-binding-material-5-datepicker-to-form-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!