(ngModelChange) 不更新特定输入的 UI [英] (ngModelChange) does not update the UI for specific input

查看:38
本文介绍了(ngModelChange) 不更新特定输入的 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,用户可以在其中输入某些东西的费率.

I have an input field where the user can enter the rate of something.

当用户输入一个值时,我希望它在四舍五入后显示,然后更新的值存储在 ts 文件中的支持模型上.

When the user enters a value, I want it to be displayed after rounding it off and then the updated value to be stored on the backing model in ts file.

使用 Angular 管道对此不利,因为一个方向的管道和更新的值不会反映在模型上.

Using an Angular pipe isn't good for this since a pipe in one directional and the updated value won't be reflected on the model.

因此,为了使其双向,我正在执行以下操作:

So to make it bidirectional, I'm doing the following:

<input type="text" [ngModel]="model.rate" (ngModelChange)="model.rate=roundRate($event)" name="rate" />

roundDate 函数看起来像这样

roundRate(value) {
    return Math.round(value);
}

现在,当我输入 5.6、7.8、9.5 等值时,它们都被四舍五入、显示并存储在模型上分别为 6、8 和 10,这是预期的行为.

Now when I enter values like 5.6, 7.8, 9.5 etc they're all rounded off, displayed and stored on the model to 6, 8 and 10 respectively, which is the expected behavior.

当我输入 2.1、3.4、5.3 等时,问题就开始了.在这种情况下,roundRate 函数被调用并返回四舍五入后的值.但是屏幕上显示的值仍然是旧值 (2.1, 3.4, 5.3)

The problem starts when I enter 2.1, 3.4, 5.3 etc. In this case, the roundRate function gets called and it returns the value after rounding off. But the values shown on screen are still the old values (2.1, 3.4, 5.3)

我检查了 Chrome 上的 input 元素,发现 ng-reflect-model 属性正在更新为预期值(2、3、5).

I inspected the input element on Chrome and found that the ng-reflect-model property was getting updated to the expected values (2, 3, 5).

<input _ngcontent-c39="" name="rate" type="text" ng-reflect-name="rate" ng-reflect-model="5" class="ng-valid ng-dirty ng-touched">

有人可以解释一下这里发生了什么,尽管 ng-reflect-model 属性得到更新,为什么屏幕仍然显示旧值?

Can someone please explain what is happening here and despite the ng-reflect-model property getting updated why the screen still shows the old values?

感谢您的帮助!

推荐答案

为了更清晰的实现,只需使用 (change) @Output 属性和 [(ngModel)].roundRate 的实现将改变如下:

For a cleaner implementation, just use the (change) @Output property and [(ngModel)]. The implementation of roundRate will change something like this:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  model = { rate: null };

  roundRate() {
    this.model.rate = Math.round(+this.model.rate);
  }
}

在模板中:

<input type="text" [(ngModel)]="model.rate" (change)="roundRate()" name="rate" />

PS:这只会在您blur从输入字段中更新值

PS: This will update the value only once you blur from your input field

这是一个 示例 StackBlitz 供您参考.

Here's a Sample StackBlitz for your ref.

这篇关于(ngModelChange) 不更新特定输入的 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆