首页 > 解决方案 > Angular Material DatePicker 允许字符串值

问题描述

我正在尝试保留 Angular Material Date 选择器输入框,并输入 DD/MMM/YYYY 或 MMM/YYYY 或(任何字符串值)要求用户单击按钮获取(任何字符串值)并分配日期选择器输入盒子

html

<a mat-flat-button (click)="Datepiker()">s</a>
  </mat-icon>
  <input matInput
         placeholder="Course Completion" 
         formControlName="Completion" maxlength="60"
         #courseCompte
         (click)="course.open()"
         [matDatepicker]="course"
         (keyup)="Compte.value =Compte.value.toUpperCase()"/>
  <mat-datepicker #course></mat-datepicker> 

TS

Datepiker() { 
 this.mainForm.get(this.formgroupName).get('Completion').setValue("Provide");
}

标签: angulardatepickerangular-materialangular-date-format

解决方案


我想出的只有一种方法可以完成(我认为)你想要的,它如下:

您将组件的元素引用注入为:

constructor(private elemRef: ElementRef){}

并使用它来获取 mat 试图从您那里抽象出来的本机输入,一旦您拥有该元素,您就可以将其输入设置为您想要的任何内容。

For example you can set it's value to 'is provided' in the following way:

 let inputElement = this.elemRef.nativeElement.querySelector('.mat-input-element.mat-datepicker-input');
 inputElement.value = 'is provided';

naturally the above code can be used in your onClick method changing the value of the element, like here: https://stackblitz.com/edit/angular-pfaxp1-fasyhy?file=src/app/datepicker-overview-example.ts

That being said, I find this solution very very ugly and hacking and I would not really want to use something like this unless I had absolutely no other choice.

Also note that the material field does not show any animation if you inject a value in the field directly as the animation is triggered by focus, so you will not get a nice animation unless you focus the element and wait for the animation to finish, as you can see here: https://stackblitz.com/edit/angular-pfaxp1-srcvv3?file=src/app/datepicker-overview-example.ts

总而言之,这是一个非常糟糕的解决方案,但我认为 Material 不允许你干净地做你想做的事。我建议你重新考虑你的设计并尝试一个替代的和干净的解决方案,如果不可能的话,我希望我给你一些关于如何以某种方式前进的想法:)


推荐阅读