Collect Date and Time in a Reactive Form

Asked

Viewed 162 times

0

I am developing a reactive form at Angular 5 and would like to store the Date/Time in a Datetime. In this case, the user should somehow inform the date and time of a specific event. However, I couldn’t find a way to store in formControlName this data directly in the view. Has anyone gone through it? What solution was adopted?

I am doing something that looks like a gambiarra. I created datetime in formBuilder and put as input Hidden in the view. Then I put a timepicker and a datepicker together the two in the component and step through ngModel to the datetime. It seems like a bit of a gambit, so I’d like to find other ways to work it out.

In HTML, I did it this way:

  <div class="row">
    <div class="input-field col s6 m6 l6">
      <input materialize="pickadate" type="text" class="datepicker" placeholder="Selecione a Data" [materializeParams]=datePickerParams
        [(ngModel)]="data" (ngModelChange)="atualizaData($event)" [ngModelOptions]="{standalone: true}">
      <label> Data </label>
    </div>
    <div class="input-field col s6 m6 l6">
      <input materialize="pickatime" type="text" class="timepicker" placeholder="Selecione a Hora" [materializeParams]="[{twelvehour: false}]"
        [(ngModel)]="hora" (ngModelChange)="atualizaHora($event)" [ngModelOptions]="{standalone: true}">
      <label> Hora  </label>
    </div>
    <input type="hidden" formControlName="dataHora" [(ngModel)]="dataHora">

That is, I put two input with ngModel, one responsible for picking the date and the other to pick the time. There I am putting right after a Hidden input that receives the dateHora, that I work there in the Component.ts, concatenating with the Moment.js:

  atualizaData($event) {
    this.dataHora = moment($event + ' ' + this.hora, 'DD/MM/YYYY HH:mm');
  }

  atualizaHora($event) {
    this.dataHora = moment(this.data + ' ' + $event, 'DD/MM/YYYY HH:mm');
  }

I do not know if this would be the best way to solve this issue, the code ended up getting a little dirty.

No answers

Browser other questions tagged

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