Abnormal behavior when taking data from a Formgroup with Angular

Asked

Viewed 253 times

2

I was finishing a form using Angular and Materialize and noticed that I was not receiving the data from fields generated with "datepicker" of Materialize, even if they have valid text.

HTML:

<form [formGroup]="dataForm" (ngSubmit)="ngSubmit()">
  <div class="input-field">
    <input
      id="my_data"
      type="text"
      formControlName="my_data"
      placeholder="dd/mm/yyyy"
      class="datepicker"/>
    <label for="my_data">Data escolhida</label>
  </div>
  <div>
    <button class="btn-large blue pf-block" type="submit">Salvar</button>
  </div>
</form>

Component initialization and form issuance:

Initializing the component:

ngOnInit() {
  setTimeout(() => {
    var elems = document.querySelectorAll('.datepicker');
    var instances = M.Datepicker.init(elems, {
      format: "dd/mm/yyyy"
    });

  this.operationForm = this.formBuilder.group({
    my_data: ['', Validators.required],
  });
}

Using the function ngSubmit() to analyze the values returned by the field:

ngSubmit(){
    console.log("my_data");
    console.log(this.operationForm.get("my_data"));
    console.log(this.operationForm.get("my_data").value)
    console.log(document.getElementById("my_data").nodeValue)
}

Date selection with Picker:

selecionando a data com o picker

campo com a data já selecionada

Resultado da emissão:

resultado dos logs no console

It is possible, even, to notice that the system interprets the field as having as value an empty string, as it is possible to see below:

valor armazenado dentro do objeto

How to make the field content read correctly (returning the "10/23/2019" string) instead of an empty string?

Updating: tried to remove boot options from the element by switching M.Datepicker.init(elems, {format: "dd/mm/yyyy"}); for M.Datepicker.init(elems);. The problem persisted.

Updating: I’m trying to avoid using the jQuery by some conflicts that he was generating with certain components when manipulating the DOM. So if you can do it using pure javascript or typescript, it would be more interesting. Thank you.

2 answers

3


Remove the form control from the input, as we will get the value explicitly

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

In this example, we get the selected date and update the value form control with the same.

var elems = document.querySelectorAll('.datepicker');
var instances = M.Datepicker.init(elems, {
    format: "dd/mm/yyyy",
    onSelect: function(dateText) {
        this.operationForm.controls['my_data'].setValue(dateText);
    },
});
  • You can do this without using jQuery?

  • Yeah, I’ll edit it out

  • and if I have two fields, with different ids (such as enter_at and exit_at)?

  • @Arthursiqueira detail better on another question

0

Salve @Arthur Siqueira.

So try Datepicker’s call:

<script>
$('#my_data').datepicker({ 
        minDate: 0,
        dateFormat: 'dd/mm/yy',
        monthNames: ['Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
        monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
        dayNames: ['Domingo', 'Segunda-feira', 'Ter&ccedil;a-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'S&aacute;bado'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'S&aacute;b'],
        dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'S&aacute;b']
    });
</script>

In addition to customizing the name of the months and days of the week to Portuguese, you have a greater control of the rules that can be used in Datepicker.

Note: "minDate: 0" serves to set only future values on the date, if not your case just remove.

Your input would look like this:

<input type="text" name="my_data" id="my_data" autocomplete="off" class="inputData_false" placeholder="Clique e escolha um dia">

Below a small script to prevent the insertion of any content that is not expected in the datepicker input:

<script>
    $(".inputData_false").on("keydown", function() {
      event.preventDefault();
      return false;
    });
</script>

Remember to always import the latest jQuery UI version into your project to avoid bugs (it is currently in version 1.12.4).

https://jqueryui.com/datepicker/

I hope I helped.

Browser other questions tagged

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