此方法用于为输入添加千位分隔符。它将删除非数字字符,然后 pip 将在 View 中添加分隔符。 但是当输入类似于“12hy ”时,它不起作用。如果输入类似于“12hy6 ”,它将给出预期的输出,如“126 ”。
我不明白什么?在调试过程中,模型实际上按预期更改。但 View 是相同的。
模型中的代码是这样的 ->
public onInputChange(event: string , id: any): any {
switch (id) {
case 'mgtFeeFromValue': {
this.mgtFeeFromValue = this.changeText(event);
console.log(this.mgtFeeFromValue);
break;
}
default: {
this.loggerService.logError('Cannot find case in switch statement line : 730');
break;
}
}
}
public changeText(str: string): any {
if (typeof str === 'string') {
const formattedNumber = parseFloat(str.replace(/\D/g, ''));
return formattedNumber;
} else if (typeof str === 'number') {
return str;
}
}
在 View 中->
<input
[ngModel]="mgtFeeFromValue | number:'1.0-5'"
(ngModelChange)="onInputChange($event ,'mgtFeeFromValue')"
maxlength="8"
class="reset-input-style w-100 text-right"
>
这是一个工作示例 ->
https://stackblitz.com/edit/angular-g5l4ra?embed=1&file=src/app/app.component.ts
最佳答案
尝试这个解决方案。
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { DecimalPipe } from '@angular/common';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ],
providers: [DecimalPipe]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { DecimalPipe } from '@angular/common';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
public mgtFeeFromValue: any;
constructor(private _decimalPipe: DecimalPipe) {}
public onInputChange(event: string , id: any): any {
console.log(event, id)
switch (id) {
case 'mgtFeeFromValue': {
let temp = this.changeText(event);
this.mgtFeeFromValue = this._decimalPipe.transform(temp, '1.0-5');
// console.log(this.mgtFeeFromValue);
break;
}
default: {
console.log('Shit happens');
break;
}
}
}
public changeText(str: string): any {
if (typeof str === 'string') {
const formattedNumber = parseFloat(str.replace(/\D/g, '').concat(' '));
return formattedNumber;
} else if (typeof str === 'number') {
return str;
}
}
}
app.component.html
<input
type="text"
[(ngModel)]="mgtFeeFromValue"
(keyup)="onInputChange($event.target.value ,'mgtFeeFromValue')"
>
如果您仍然遇到问题,请告诉我。
关于javascript - 仅在某些情况下 View 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59782179/