Angular 8 datepicker禁用输入,仅使用日历和提交按钮已禁用

问题描述 投票:0回答:2

以反应式Angular形式,我想禁用输入,因此用户仅使用日历。我用这个:HTML

<mat-form-field>
    <mat-label for="date">Starting date : </mat-label>
    <input matInput [matDatepicker]="date" [min]="startDate" placeholder="mm/dd/yyyy" formControlName="date" disabled>
    <mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
    <mat-datepicker #date disabled="false"></mat-datepicker> <mat-error *ngIf="form.controls['date'].invalid">{{getErrorMessage('date')}}</mat-error>
</mat-form-field>

[提交按钮

<button type="submit" [disabled]="form.invalid">Create project</button>

TS

ngOnInit() {
  this.form = new FormGroup({
    date: new FormControl({ disabled: true, value: '' }, [Validators.required])
    })
}

它有效(输入被禁用并且日历有效),但是问题出在我的提交按钮上。如果另一个必填字段为空,则禁用提交按钮。但是,如果未使用日期选择器选择日期(并且其他必填字段有输入),则不会禁用提交按钮。

我在浏览器控制台中也有一条警告消息:>

  It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
  when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
  you. We recommend using this approach to avoid 'changed after checked' errors.

  Example: 
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

>

angular button datepicker submit disable
2个回答
1
投票

Angular不会触发禁用字段的验证器。我认为您可以解决将输入禁用更改为readonly模式的按钮问题。

例如:

HTML

<mat-form-field>
    <mat-label for="date">Starting date : </mat-label>
    <input matInput [matDatepicker]="date" [min]="startDate" placeholder="mm/dd/yyyy" formControlName="date" readonly >
    <mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
    <mat-datepicker #date disabled="false"></mat-datepicker> <mat-error *ngIf="form.controls['date'].invalid">{{getErrorMessage('date')}}</mat-error>
</mat-form-field>

TS:

ngOnInit() {
  this.form = new FormGroup({
    date: new FormControl( '' ,Validators.required])
    })
}

它将通过浏览器警告和所需的验证(我认为)解决您的问题。


0
投票

如角度材料文档所说,要在材料日期选择器上禁用输入按钮,请使用:

<mat-form-field>
    <input matInput [matDatepicker]="dp3" placeholder="Input disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp3"></mat-datepicker-toggle>
    <mat-datepicker #dp3 disabled="false"></mat-
</mat-form-field>

您做对了,但是为什么要用disable true初始化日期?

date: new FormControl({ disabled: true, value: '' }, [Validators.required])

@ Leandro说的对,我也建议调整表格使其可点击以获得适当的用户体验:

  <mat-form-field  >
    <input matInput [matDatepicker]="dp3" placeholder="Select a date" formControlName="date" readonly (click)="dp3.open()" style="cursor: pointer;">
    <mat-datepicker-toggle matSuffix [for]="dp3"></mat-datepicker-toggle>
    <mat-datepicker #dp3 disabled="false"></mat-datepicker>
  </mat-form-field>
© www.soinside.com 2019 - 2024. All rights reserved.