简体   繁体   English

带有 mat-datepicker-toggle 问题的 mat 输入

[英]mat input with mat-datepicker-toggle problem

I have a form where every required field turns red if the user clicks and blur the field without writing anything on the field, the problem comes with this date picker我有一个表单,如果用户单击并模糊该字段而不在该字段上写任何内容,则每个必填字段都会变成红色,这个日期选择器会出现问题

        <mat-form-field class="contenedorFecha" appearance="outline" color="accent">
        <mat-label>Fecha plantación</mat-label>
        <input matInput [matDatepicker]="fechaPlantacion" formControlName="fechaPlantacion" readonly (click)="fechaPlantacion.open()">
        <div matSuffix style="display:flex; align-items: center">
            <mat-datepicker-toggle [for]="fechaPlantacion"></mat-datepicker-toggle>
            <button mat-icon-button (click)="deleteDate('fechaPlantacion', $event)" [disableRipple]="true" 
            *ngIf="fincaForm.get('fechaPlantacion').value !== null">
                <mat-icon class="nav-link-icon mat-icon notranslate material-icons mat-icon-no-color ng-star-inserted" role="img" aria-hidden="true">close</mat-icon>
            </button>
        </div>
        <mat-datepicker #fechaPlantacion></mat-datepicker>
    </mat-form-field>

When I click on the input it opens the matDatePicker, but as it opens the date picker the input blurs, so the input changes to red, any way to prevent this?当我单击输入时,它会打开 matDatePicker,但是当它打开日期选择器时,输入会变得模糊,因此输入会变为红色,有什么办法可以防止这种情况发生? I've tried with css but the problem is I want the input to be red but only when it should我试过使用 css 但问题是我希望输入是红色的但只有在它应该的时候

Yes the problem is because the focus gets out of the input control and goes to the calendar.是的,问题是因为焦点离开了输入控件并转到了日历。 If you are only using the default button as the trigger to open the date picker, then you won't encounter this issue.如果您仅使用默认按钮作为打开日期选择器的触发器,则不会遇到此问题。 But like what you did, sometimes it's better to add that (focus) or (click) trigger.但就像您所做的那样,有时最好添加那个(focus)(click)触发器。 I can only think of one work around.我只能想到一种解决方法。

Start by removing the initial validators from your field.首先从您的领域中删除初始验证器。 Then put a handler whenever the material date picker was closed such as:然后在材料日期选择器关闭时放置一个处理程序,例如:

<mat-datepicker #fechaPlantacion (closed)="close()"></mat-datepicker>

and in the close method, you have to set the validators dynamically:在 close 方法中,您必须动态设置验证器:

  close() {
    this.fechaPlantacion.setValidators(Validators.required);
    this.fechaPlantacion.updateValueAndValidity(null);
  }

This way, the validation will only be added after the selection (or not selecting anything) from the dates in the calendar.这样,验证只会在从日历中的日期中选择(或不选择任何内容)之后添加。 I also tried using readonly input and still working fine after testing in my local machine.我还尝试使用readonly输入,并且在我的本地机器上测试后仍然工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM