我试图在反应式表单中使用重要的日期选择器,但是由于更改连接到日期选择器的输入的值不会更新表单控件的值,因此我遇到了问题。
因此,这会导致各种问题,例如不正确的验证错误,例如尽管填充了输入,但仍显示所需的错误,并且表单未归类为有效,这意味着应该在应有的状态下未启用按钮。
component.html
<form [formGroup]="invoiceForm">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Date</mat-label>
<input matInput formControlName="date" [matDatepicker]="selectDate" placeholder="DD/MM/YYYY">
<mat-datepicker-toggle matSuffix [for]="selectDate"></mat-datepicker-toggle>
<mat-datepicker #selectDate></mat-datepicker>
<mat-error *ngIf="form.date.errors.required">Date is required</mat-error>
<mat-error *ngIf="form.date.errors.validDate">Invalid date</mat-error>
</mat-form-field>
<button mat-raised-button (click)="saveInvoice()" [disabled]="!invoiceForm.valid || !items.length">Save</button>
</form>
component.ts
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable, from } from 'rxjs';
import { MatPaginator, MatSort, MatTableDataSource, MatDialog, MatDialogRef, MatDatepickerInputEvent } from '@angular/material';
import * as moment from 'moment';
import { DataService } from '@app/services/data/data.service';
import { ContactsService } from '@app/services/contacts/contacts.service';
// import { NewContactDialogComponent } from './dialogs/new-contact-dialog/new-contact-dialog.component';
import { NewItemDialogComponent } from '@app/invoices/dialogs/new-item-dialog/new-item-dialog.component';
import Invoice from '@app/interfaces/invoice.interface';
import InvoiceItem from '@app/interfaces/invoiceItem.interface';
import ValidateDate from '@app/validators/date.validator';
@Component({
selector: 'app-new-invoice',
templateUrl: './new-invoice.component.html',
styleUrls: ['./new-invoice.component.scss']
})
export class NewInvoiceComponent implements OnInit {
invoice: Invoice;
invoiceForm: FormGroup;
items: InvoiceItem[];
constructor(public data: DataService, public contactsService: ContactsService, private formBuilder: FormBuilder, private dialog: MatDialog) {
this.items = [];
this.invoiceForm = this.formBuilder.group({
id: ['', Validators.required],
reference: ['', Validators.required],
contactId: ['', Validators.required],
date: [
'',
[
Validators.required,
ValidateDate
]
],
saleDate: [
'',
Validators.required,
ValidateDate
],
dueDate: [
'',
Validators.required,
ValidateDate
]
})
}
答案 0 :(得分:0)
尝试使用
<input matInput [formControl]="date" [matDatepicker]="selectDate" placeholder="DD/MM/YYYY">