【发布时间】:2019-06-02 14:24:39
【问题描述】:
最小的 Stackblitz 示例
https://stackblitz.com/edit/angular-mqqvz1
在一个 Angular 7 应用程序中,我创建了一个带有 <input> 字段的简单组件。
当我使用键盘更改输入值时,我希望将值格式化为 onBlur。 - 在最小的示例中,我只想将字符串 " EDIT" 添加到它。
这基本上是有效的:
- 如果我输入“test”并模糊该字段,它将更改为“test EDIT”
- 如果我输入“lala”并模糊该字段,它将更改为“lala EDIT”
但是 当我输入“test” - blur(它有效)并再次输入“test”时,它不再有效!
onInputUpdate() 函数被调用(您可以在控制台日志中看到它),变量 inputValue 被更新(您可以在组件 {{inputValue}} 中看到它),但是输入值不变!
我希望它是“测试编辑”,但它仍然是“测试”。
当我输入另一个字符串时它可以工作,但是连续输入相同的字符串 2 次不起作用。这是为什么?我该如何解决这个问题?
component.html
{{inputValue}} <br />
<input type="text"
[ngModel]="inputValue"
(ngModelChange)="onInputUpdate($event)"
[ngModelOptions]="{ updateOn: 'blur' }"/>
component.ts
@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)
}
}
【问题讨论】:
-
updateOn标志是否存在远离默认change的特定情况? -
尝试制作自己的 onFocus 来重置它? stackoverflow.com/questions/32019330/…
-
我只希望值更新 onBlur,这就是为什么我设置了 ` [ngModelOptions]="{ updateOn: 'blur' }`
标签: angular angular-ngmodel angular-components angular7 angular-changedetection