最小StackBlitz示例
https://stackblitz.com/edit/angular-mqqvz1
在Angular7应用程序中,我创建了一个简单的组件,
<input>
字段。
当我用键盘更改输入值时,我希望对该值进行格式化
失去焦点
. -在最小示例中,我只想添加字符串
“编辑”
对它。
这基本上是可行的:
-
如果我键入“test”并模糊字段,它将更改为“test edit”
-
如果我输入“lala”并模糊字段,它将更改为“lala edit”
然而
当我输入“test”(测试)模糊(它有效)并再次输入“test”(测试)时,它就不再有效了!
这个
onInputUpdate()
-函数被调用(可以在控制台日志中看到),变量
inputValue
更新(您可以在组件中看到它
{{inputValue}}
)
但是输入值不变!
我希望它是“测试编辑”,但它保持“测试”。
当我键入另一个字符串时,它是有效的,但是在同一个字符串中连续键入2次是无效的。为什么?我怎么修这个?
组件HTML
{{inputValue}} <br />
<input type="text"
[ngModel]="inputValue"
(ngModelChange)="onInputUpdate($event)"
[ngModelOptions]="{ updateOn: 'blur' }"/>
组件
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
inputValue = "teststring";
constructor(
private changeDetectorRef: ChangeDetectorRef,
) {}
public ngOnInit() {
this.inputValue = "initial";
}
public onInputUpdate(inputValue: string) {
this.inputValue = inputValue + ' EDIT';
this.changeDetectorRef.markForCheck();
console.log('onInputUpdate new inputValue', this.inputValue)
}
}