datepicker中获取价值

datepicker中获取价值

本文介绍了从FormControl中的mat-datepicker中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建对API的POST请求,并且引发错误的字段之一是 mat-datepicker 字段,因为它位于 ngOnInit()内部通话(我想还没有选择).诸如 name email 之类的字段表现良好,但是我无法从datepicker字段中获取一个值...我也该如何发送该值提交表单时是什么?

I am creating a POST request to an API, and one of the fields which throws an error is a mat-datepicker field, since it's inside the ngOnInit() call(and nothing is yet selected, I guess). Fields such as name, email etc. behave well, but I'm having trouble getting a value out of the datepicker field... How could I send that value as well when submitting the form?

我的尝试是这样:

ngOnInit() {
  this.myForm = new FormGroup({
    date_of_birth: new FormControl(new Date().toISOString(), [
       Validators.required,
       this.backendValidation.bind(this, 'date_of_birth')
    ])
   })
  }


<mat-form-field>
  <mat-label>Date</mat-label>
  <input matInput [matDatepicker]="date_of_birth" formControlName="date_of_birth" />
  <mat-datepicker-toggle matSuffix [for]="date_of_birth"></mat-datepicker-toggle>
  <mat-datepicker #date_of_birth></mat-datepicker>
</mat-form-field>

推荐答案

在HTML中:

<form [formGroup]="empForm" (ngSubmit)="onSubmit()">
<mat-form-field>
    Date
    <input matInput [matDatepicker]="picker" formControlName="date_of_birth" />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</form>

<button (click)="get()">get</button>

TS:

this.empForm = this.fb.group({
  date_of_birth: new FormControl(new Date(), [
    Validators.required
  ])
});

要控制台:

get(){
 console.log(this.empForm.get('date_of_birth').value);
}

希望这会对您有所帮助.如果有任何问题,那么我认为您的自定义验证程序存在问题- this.backendValidation.bind(this,'date_of_birth').

Hope this will help you. If any issues, then I think its problem with the custom validator you have - this.backendValidation.bind(this, 'date_of_birth').

希望这行得通!

这篇关于从FormControl中的mat-datepicker中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-25 22:36