0

In my Angular-12 project, I am using Material datepicker. I have done this in the Material Module:

Material.Module:

import {
  NgModule
} from '@angular/core';
import {
  CommonModule
} from '@angular/common';
import {
  MatDatepickerModule
} from '@angular/material/datepicker';
import {
  MatMomentDateModule,
  MomentDateAdapter
} from '@angular/material-moment-adapter';
import {
  MAT_DATE_LOCALE,
  DateAdapter,
  MAT_DATE_FORMATS
} from '@angular/material/core';
import {
  MatFormFieldModule
} from '@angular/material/form-field';

const MY_FORMATS = {
  parse: {
    dateInput: 'DD/MM/YYYY',
  },
  display: {
    dateInput: 'DD/MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'DD/MM/YYYY',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

class AdpDateAdapter extends MomentDateAdapter {
  constructor(dateLocale: string) {
    super(dateLocale);
  }

  getFirstDayOfWeek(): number {
    return 1;
  }
}


@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    MatAutocompleteModule,
    MatCheckboxModule,
    MatDatepickerModule,
    MatMomentDateModule,
    MatFormFieldModule,
  ],
  providers: [{
      provide: DateAdapter,
      useClass: AdpDateAdapter,
      deps: [MAT_DATE_LOCALE]
    },
    {
      provide: MAT_DATE_FORMATS,
      useValue: MY_FORMATS
    },
  ],
  exports: [
    MatAutocompleteModule,
    MatCheckboxModule,
    MatDatepickerModule,
    MatMomentDateModule,
    MatFormFieldModule,
  ]
})
export class MaterialModule {}

Then imported it Auth.Module where I'm to use it:

import { MaterialModule } from '../../material/material.module'; imports: [ CommonModule, MaterialModule, ReactiveComponentModule, AuthRoutingModule, ],

component:

import {
  Moment
} from 'moment';
dateValue: any;
@Input() max: any;
tomorrow = new Date();

constructor(
  private fb: FormBuilder,
  private api: ApiService,
) {
  this.tomorrow.setDate(this.tomorrow.getDate());
}

ngOnInit() {
  this.companyForm = this.fb.group({
    companyName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(100)]],
    dateEstablished: ['', [Validators.required]]
  }, {
    updateOn: "blur"
  });
  this.idForm = this.fb.group({
    registrationNumber: ['', [Validators.required, Validators.maxLength(100)]],
  });
}

get fc() {
  return this.companyForm.controls;
};
get fi() {
  return this.idForm.controls;
};

onSubmit() {
  this.isSubmitted = true;

  const formCompanyData = this.companyForm.getRawValue();
  const formIdData = this.idForm.getRawValue();

  const data = {
    companyName: formCompanyData.companyName,
    dateEstablished: formCompanyData.dateEstablished,
    registrationNumber: formCompanyData.registrationNumber,
  };

  this.spinnerService.show();
  const header = {
    'Content-Type': 'application/json'
  };

  this.isLoading = true;
  return this.api.post('signup', data, header)
    .pipe(first())
    .subscribe(
      data => {
        this.tokenHandler(data);
      });
}
}

HTML:

    <mat-horizontal-stepper [linear]="isLinear" #stepper labelPosition="bottom">
      <mat-step [stepControl]="companyForm">
        <form [formGroup]="companyForm">
          <ng-template matStepLabel matStepperIcon="phone">Company Info</ng-template>

                    <div class="col-12 col-md-4">
                      <div class="form-group">
                        <label for="dateEstablished">Date Registered:<span style="color:red;">*</span></label>
                        <mat-form-field>
                          <input matInput [matDatepicker]="picker"   placeholder="Choose a date" [max]="tomorrow" formControlName="dateEstablished"
                          readonly required>
                          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                          <mat-datepicker #picker></mat-datepicker>
                        </mat-form-field>
                      </div>
                      <div *ngIf="fc.dateEstablished.touched && fc.dateEstablished.invalid">
                        <div *ngIf="fc.dateEstablished.hasError('required')">
                          <div class="text-danger">
                            Date Registered is required!
                          </div>
                        </div>
                      </div>
                    </div>

          <div class="col-12 col-md-8">
            <div class="form-group">
              <label for="name">Company Name:<span style="color:red;">*</span></label>}
              <input type="text" formControlName="companyName" placeholder="Company Name" class="form-control" required/>
            </div>
            <div *ngIf="fc.companyName.touched && fc.companyName.invalid">
              <div *ngIf="fc.companyName.hasError('required')">
                <div class="text-danger">
                  Company Name is required!
                </div>
              </div>
              <div *ngIf="fc.companyName.hasError('minlength')">
                <div class="text-danger">
                  Company Name cannot be less than 3 characters!
                </div>
              </div>
              <div *ngIf="fc.companyName.hasError('maxlength')">
                <div class="text-danger">
                  Company Name cannot be more than 100 characters!
                </div>
              </div>
            </div>
          </div>
          <div class="card-footer">
            <button mat-raised-button color="primary" matStepperNext [disabled]="companyForm.status != 'VALID'">Next</button>
          </div>
        </form>
      </mat-step>
      <mat-step [stepControl]="idForm">
        <form [formGroup]="idForm">
          <ng-template matStepLabel>Company ID</ng-template>
          <div class="col-12 col-md-12">
            <div class="form-group">
              <label for="registration_number">Registration Number:<span style="color:red;">*</span></label>
              <input type="text" formControlName="registrationNumber" placeholder="Registration Number" class="form-control" required/>
            </div>
            <div *ngIf="fi.registrationNumber.touched && fi.registrationNumber.invalid">
              <div *ngIf="fi.registrationNumber.hasError('required')">
                <div class="text-danger">
                  Company Reg. No. is required!
                </div>
              </div>
              <div *ngIf="fi.registrationNumber.hasError('maxlength')">
                <div class="text-danger">
                  Company Reg. No. cannot be more than 100 characters!
                </div>
              </div>
            </div>
          </div>
          <div class="card-footer">
            <button mat-raised-button color="black" matStepperPrevious>Back</button> &nbsp;
            <button mat-raised-button color="success" [disabled]="isLoading" type="submit" (click)="onSubmit()">
                        <span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span>
                          Submit
                      </button> &nbsp;
            <button mat-raised-button color="warn" (click)="stepper.reset()">Reset</button>
          </div>
      </mat-step>
    </mat-horizontal-stepper>

I got this response in the console:

{companyName: "ssasa", : registrationNumber: "sasaas", …}
companyName: "ssasa"
registrationNumber: "sasaas"
company_logo: "C:\\fakepath\\token.PNG"
dateEstablished: Moment
_d: Thu Jul 22 2021 00:00:00 GMT+0100 (West Africa Standard Time) {}
_i: {year: 2021, month: 6, date: 22}
_isAMomentObject: true
_isUTC: false
_isValid: true
_locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", 
_dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, …}
_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -1, charsLeftOver: 0, …}
__proto__: Object

The data not being saved into the DB.

console.log(data.dateEstablished); gives:

Moment {
  _isAMomentObject: true,
  _i: {…},
  _isUTC: false,
  _pf: {…},
  _locale: Locale,
  …
}
_d: Sun Jul 18 2021 00: 00: 00 GMT + 0100(West Africa Standard Time) {}
_i: {
  year: 2021,
  month: 6,
  date: 18
}
_isAMomentObject: true
_isUTC: false
_isValid: true
_locale: Locale {
  _calendar: {…},
  _longDateFormat: {…},
  _invalidDate: "Invalid date",
  _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  ordinal: ƒ,
  …
}
_pf: {
  empty: false,
  unusedTokens: Array(0),
  unusedInput: Array(0),
  overflow: -1,
  charsLeftOver: 0,
  …
}
__proto__: Object

How do I get this date issue sorted out and save dateEstablished into the DB?

Thanks

midowu
  • 937
  • 5
  • 19
  • 40
  • If you add `console.log(data.dateEstablished)`, what result is shown? "Date string" or Moment object. Anyway, can you try to create a Minimal, Reproducible Example on [StackBlitz](https://stackblitz.com) so we can check the root cause? Thank you. – Yong Shun Jul 24 '21 at 01:44
  • @YongShun - Resolved. When I did dateEstablished: new Date(formCompanyData.dateEstablished).toISOString(), I got "2021-07-18T23:00:00.000Z". I think that is okay. Thanks – midowu Jul 24 '21 at 08:15
  • @YongShun - Can you assist on this? - https://stackoverflow.com/questions/68498047/angular-call-to-a-member-function-getclientoriginalextension-on-null-excep – midowu Jul 24 '21 at 08:20
  • Good to see you get the answer. Meanwhile, for your second comment, you shouldn't post to request to review other question. – Yong Shun Jul 24 '21 at 08:44
  • @YongShun - Okay, I've taken to correction. Thanks. Just – midowu Jul 24 '21 at 08:49

0 Answers0