Search code examples
angulartypescriptangular-materialangular-ngmodel

([ngmodel]) object does not refresh data when it is changed in a method


everybody,

I hope you'll help me with my problem.

I'm currently generating a set of inputs through a JSON. If I modify the data in the web interface, there is no problem.

The problem comes when the value of any input, I modify it in the component, in a function for example.

It doesn't detect the changes. I have searched for information here, but I have not found the solution yet.

I leave you a link where you can see the code and the problem I have.

Stackblitz Proyect Example


Solution

  • You need to use proper bindings in the template:

    to set the value [ngModel]="form[inputs.value.name] || inputs.value.default", that allows to use the default value.

    to update the value we need to listen to the output (ngModelChange)="form[inputs.value.name] = $event".

    <input
      matInput
      type="number"
      id={{inputs.value.name}}
      [ngModel]="form[inputs.value.name] || inputs.value.default"
      (ngModelChange)="form[inputs.value.name] = $event"
      placeholder={{inputs.value.minimum}}
      min={{inputs.value.minimum}}
      max={{inputs.value.maximum}}
      step={{inputs.value.step}}
      matTooltip="{{inputs.value.title}}: {{inputs.value.description}}"
      matTooltipPosition="before"
      style="text-align: right;"
    />