[英]Expression Changed after it has been checked Angular
我有這個用於上傳文檔的輸入,我正在嘗試檢查它是否為空以顯示警報。
這是我的代碼:
<div class="form-group">
<input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint"
(change)="onUpload($event)">
<input type="text" #documentLink class="form-control" name="urlDocument" [value]="urlDocument | async">
</div>
<div *ngIf="!documentLink.value" class="alert alert-danger">
Imaginea de coperta este necesara!
</div>
我有這個錯誤:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'ngIf: true'. Current value: 'ngIf: false'.
我用這個viewchild來取值
@ViewChild('documentLink', {static: false}) inputDocumentLink : ElementRef;
這就是我在數據庫中添加它的方法:
const link = this.inputDocumentLink.nativeElement.value;
...
你能幫助我嗎? 非常感謝!
問題是使用異步 pipe 並在模板中引用下面的值。
從模板中刪除異步 pipe
在 Ts 有它喜歡
public inputValue;
ngOnInit() {
this.getData();
}
public getData() {
this.urlDocument.subscribe((res) => {
this.inputValue = res;
});
}
HTML:-
<div class="form-group">
<input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint"
(change)="onUpload($event)">
<input type="text" #documentLink class="form-control" name="urlDocument" [value]="inputValue">
</div>
<div *ngIf="!inputValue" class="alert alert-danger">
Imaginea de coperta este necesara!
</div>
原因:-在瀏覽模板時,您的 url 文檔未定義,當它的另一個生命周期鈎子重新檢查模板時,它已更改,因為可觀察到發出值。 因為在正常的 ng 服務中,angular 每次更改檢測都會進行兩次,以讓您知道代碼中的異常情況。 嘗試運行 ng serve --prod 你不會得到這個錯誤。 但是你應該用我給出的方法 go 因為這個錯誤是為了避免這種違規行為。
問題是您的*ngIf
條件取決於使用數據綁定更新的輸入元素的屬性。 為避免異常,您應該參考原始數據而不是元素屬性。
下面的代碼顯示了如何繼續使用async
pipe 而不重復它。 異步結果存儲在doc
object 中,該文檔設置在包含ng-container
的*ngIf
條件中(創建 object 可確保條件始終為true
)。 然后,我們使用doc.url
作為input
和div
元素的*ngIf
條件中的值。
<ng-container *ngIf="{ url: urlDocument | async } as doc">
<div class="form-group">
...
<input type="text" #documentLink [value]="doc.url" ...>
</div>
<div *ngIf="!doc.url" ...>
Imaginea de coperta este necesara!
</div>
</ng-container>
請參閱此 stackblitz以獲取演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.