我在Angular 7应用程序中遇到问题。使用Windows 10上的Microsoft Edge进入网站的客户端似乎已启用Web表单的自动完成(或自动填充)功能。
问题在于应用程序的每个字段都有:
使用自动填充时,不会触发这些事件。无论我们使用活动表单还是模板驱动表单,由于更改来自Angular区域之外,因此绑定属性都不会更新。而且,当浏览器填充该字段时,不仅我们会丢失导致各种错误的数据,而且前端验证也会通过。该表格才有效,用户可以使用不完整的数据触发功能。
我尝试过ChangeDetectorRef,不走运。
要进行复制,您可以在Angular区域之外使用纯JS编程地更改字段的值(例如,在index.html的末尾)
// somewhere at the end of index.html
setTimeout(() => {
let field = document.getElementsByTagName('input')[0];
field.value = 'Hello World!';
field = document.getElementsByTagName('input')[1];
field.value = 'Hello World!';
}, 2500);
// ----- end of index.html snippet
// app.component.ts
export class AppComponent {
title = 'js-angular';
test = 'Hi';
fg: FormGroup;
constructor(private fb: FormBuilder) {
this.fg = this.fb.group({
test: ['Hi']
})
}
doIt() {
console.log(this.fg.get('test').value);
console.log(this.test);
}
}
// ----- end of app.component.ts snippet
<form (submit)="doIt()">
<input type="text" name="test" [(ngModel)]="test">
<button type="submit">Envoyer</button>
</form>
<form (submit)="doIt()" [formGroup]="fg">
<input type="text" formControlName="test">
<button type="submit">Envoyer</button>
</form>
我的问题是:是否有一种干净的方法来使自动填充的字段更新Angular绑定变量并触发分析事件?
我目前的解决方案是使用document.getElementById('idOfThePotentiallyAutofilledField')
请注意,此解决方案是临时的,可以减少生产错误的数量。