How to initialize two or more different date selectors in a form with Materialize?

Asked

Viewed 111 times

0

After initializing a datepicker of Materialize CSS successfully, I realized I would need two datepickers in the same form. The problem is that I can only initialize one datepicker:

HTML:

<form [formGroup]="dataForm" (ngSubmit)="ngSubmit()">
  <div class="input-field">
    <input
      id="enter_at"
      type="text"
      placeholder="dd/mm/yyyy"
      class="datepicker"/>
    <label for="enter_at">Entrou em:</label>
  </div>
  <div class="input-field">
      <input
        id="exit_at"
        type="text"
        placeholder="dd/mm/yyyy"
        class="datepicker"/>
    <label for="exit_at">Saiu em:</label>
  </div>
  <div>
    <button class="btn-large blue pf-block" type="submit">Salvar</button>
  </div>
</form>

Component initialization in Angular:

var elems = document.querySelectorAll('.datepicker');
var instances = M.Datepicker.init(elems, {
    format: "dd/mm/yyyy",
    onSelect: function(dateText) {
        this.dataForm.controls['enter_at'].setValue(dateText);
    },
});

I tried to initialize them just by clicking, but it didn’t work. The system simply ignores the property:

Modified HTML:

  <div class="input-field">
    <input
      id="enter_at"
      type="text"
      placeholder="dd/mm/yyyy"
      (click)="datapickerInitialize('enter_at')"
      class="datepicker"/>
    <label for="enter_at">Entrou em:</label>
  </div>
  <div class="input-field">
      <input
        id="exit_at"
        type="text"
        placeholder="dd/mm/yyyy"
        (click)="datapickerInitialize('enter_at')"
        class="datepicker"/>
    <label for="exit_at">Saiu em:</label>
  </div>

Function datapickerInitialize:

datapickerInitialize(id: string){
  var elems = document.getElementById(id);
  var instances = M.Datepicker.init(elems, {
    format: "dd/mm/yyyy",
    onSelect: (dateText) => {
      this.dataForm.controls[id].setValue(dateText);
    },
  });
}

I am not making use of jQuery in the project because of some DOM manipulation conflicts with some components.

How to do this startup in Javascript or pure Typescript?

1 answer

0


I managed to make it work by changing the kind of event, of (click) for (focus):

<div class="input-field">
  <input
    id="enter_at"
    type="text"
    placeholder="dd/mm/yyyy"
    (focus)="datapickerInitialize('enter_at')"
    class="datepicker"/>
  <label for="enter_at">Entrou em:</label>
</div>
<div class="input-field">
  <input
    id="exit_at"
    type="text"
    placeholder="dd/mm/yyyy"
    (focus)="datapickerInitialize('enter_at')"
    class="datepicker"/>
  <label for="exit_at">Saiu em:</label>
</div>

Functionality started to operate successfully.

Browser other questions tagged

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