0

I can not get value from mat-datepicker. It says undefined. I used ngForm and ngModel but I do not know where I am wrong.

<form #f="ngForm" (ngSubmit)="registerClient(f.value)">
    <div class="" style="width: 50%; margin:auto;">
        <!-- ... Other fields -->
        <!-- ... -->

        <div class="form-group">
            <mat-form-field id="date">
                <input matInput [matDatepicker]="picker" placeholder="Choose a date" [(ngModel)]="date">
                <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                <mat-datepicker id="datePicked" #picker></mat-datepicker>
            </mat-form-field>
        </div>
        <div>
        </div>
        <button class="btn btn-success mt-2">Add new client</button>
    </div>
</form>

client-form.ts

export class ClientFormComponent {
    date: Date;
    // ...
    // ...
    registerClient(crediantials) {
        let client: Client = {
            firstName: crediantials.firstName,
            lastName: crediantials.lastName,
            phone: crediantials.phone,
            doctorsName: this.selectedD.username,
            procedure: this.selectedP,
            registrationDate: this.date
        };

        console.log(client), 'client';
        console.log(crediantials)
        console.log(this.date, ' date);
        this.clientService.addClient(client);
    }
}

These are the errors I get in my console.

ClientFormComponent.html:41 ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

Example 1: <input [(ngModel)]="person.firstName" name="first">

Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 69, nodeDef: {…}, elDef: {…}, elView: {…}}

ERROR Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges

This is the line where the error occurs.

<input matInput [matDatepicker]="picker" placeholder="Choose a date"  [(ngModel)]="date">
nash11
  • 8,220
  • 3
  • 19
  • 55
Dignity Dignity
  • 151
  • 2
  • 11

1 Answers1

0

If ngForm is used, input fields which have ngModal must have an attribute name with a value.

<input matInput [matDatepicker]="picker" name="date" placeholder="Choose a date" [(ngModel)]="date">
Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70