javascript - 瀏覽器自動填充的欄位未更新 Angular 綁定的變數
我在一個 Angular 7 應用程式中遇到了一個問題。使用 Windows 10 上的 Microsoft Edge 瀏覽網站的客戶端似乎啟用了網頁表單的自動完成(或自動填充)。
問題是應用程式的每個欄位都有:
- 用於追蹤使用者行為的分析事件
- 自動保存功能,正在發送請求以保存數值(在更改時)
使用自動填充時,這些事件不會被觸發。無論我們使用反應式表單還是模板驅動表單,當變化來自 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') 從欄位中取得值
請注意,這個解決方案是暫時的,用來減少生產錯誤的數量。