Angular 8 / ngx-bootstrap / Datepicker

Asked

Viewed 2,253 times

0

I’m using the datepicker da ng-boostrap and I am finding it difficult to format the date that goes to the input after clicking on the desired day:

inserir a descrição da imagem aqui

I would like it to be in format: dd/mm/yyyy.

Follows HTML from input:

<input class="form-control form-control-sm" type="text" ngbDatepicker #d="ngbDatepicker" (click)="d.toggle()" [ngClass]="{ 'is-invalid': enviado && f.dt_inicial.errors?.required }" formControlName="dt_inicial">

Below is how I changed the standard locality of Angular, as well as the import of Ngbmodule:

import { registerLocaleData, DatePipe } from '@angular/common';
import localePt from '@angular/common/locales/pt';

registerLocaleData(localePt);

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

...

imports: [
    ...

    NgbModule
],
providers: [
    ...

    { provide: LOCALE_ID, useValue: 'pt' }
]
  • How is your code, Html and Typescript if possible??

  • Leandrade, first thank you for contacting, I changed the query with the codes that involve the Datepicker.

2 answers

1

Add location to Chronos

import { defineLocale } from 'ngx-bootstrap/chronos';
import { ptBrLocale } from 'ngx-bootstrap/locale';
defineLocale('pt-br', ptBrLocale); 

Then use the datapicker for this location

constructor(private localeService: BsLocaleService) {
   localeService.use('pt-br');
 }
  • There is no possible import for 'ngx-bootstrap/Chronos'/'ngx-bootstrap/Chronos', I made a change to the question where I also quote how I am importing Ngbmodule.

0

I did so using Moment:

import {
  NgbDateParserFormatter,
  NgbDateStruct
} from '@ng-bootstrap/ng-bootstrap';
import * as moment from 'moment';
import { Injectable } from '@angular/core';
@Injectable()
export class NgbDateMomentParserFormatter extends NgbDateParserFormatter {
  private momentFormat = 'DD/MM/YYYY';
  constructor() {
    super();
  }
  format(date: NgbDateStruct): string {
    if (date === null) {
      return '';
    }
    let d = moment({ year: date.year, month: date.month - 1, date: date.day });
    return d.isValid() ? d.format(this.momentFormat) : '';
  }

  parse(value: string): NgbDateStruct {
    if (!value) {
      return null;
    }
    let d = moment(value, this.momentFormat);
    return d.isValid()
      ? { year: d.year(), month: d.month() + 1, day: d.date() }
      : null;
  }
}

In your module:

  providers: [
    {
      provide: NgbDateParserFormatter,
      useClass: NgbDateMomentParserFormatter
    }
  ]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.