![](/img/trans.png)
[英]ExpressionChangedAfterItHasBeenCheckedError assigning value to array in subscribe
[英]Assigning value to input field showing error: ExpressionChangedAfterItHasBeenCheckedError
我正在從本地存儲中拆分一個字符串並將其放入數組中,如下所示:
file.ts
getskills: Array<string> = [];
// a,b,c is the value in getskills
ionViewDidLoad() {
this.getskills = JSON.parse(localStorage.getItem("profskill")).split(',');
console.log(this.getskills[1]);
// The answer is b in console window
}
現在在我的file.html
有一個輸入字段,我希望它的值是this.getskills[1]
但是當我分配這個時我得到以下錯誤:
運行時錯誤 ExpressionChangedAfterItHasBeenCheckedError:檢查后表達式已更改。 以前的值:''。 當前值:'b'。
file.html
代碼供參考:
<ion-item>
<ion-input [(ngModel)]="skills" type="text" #skills1 (keyup.enter)="save(skills1.value); skills1.value='' " placeholder="skills" [value] = "getskills[0] ? getskills[0]: ''"></ion-input>
</ion-item>
如何將該值分配給我的輸入字段?
如果您的更新發生在 Angular 檢查視圖之后,就會發生這種情況。
快速而骯臟的方式是;
注入 ChangeDetectorRef
constructor(private changeDetectorRef:ChangeDetectorRef){}
ionViewDidLoad() {
this.getskills = JSON.parse(localStorage.getItem("profskill")).split(',');
console.log(this.getskills[1]);
// The answer is b in console window
this.changeDetectorRef.detectChanges();
// run the change detection manually
}
但是解決這類問題的正確方法是將您的更新( ionViewDidLoad
)移動到更好的時刻。
不要忘記,當您對模型進行更改(`getskills')時,您需要確保 Angular 遠離它。
編輯:
ionViewDidLoad() {
this.skills = JSON.parse(localStorage.getItem("profskill")).split(',')[0];
console.log(this.getskills[1]);
// The answer is b in console window
this.changeDetectorRef.detectChanges();
// run the change detection manually
}
和
<ion-item>
<ion-input [(ngModel)]="skills" type="text" #skills1 (keyup.enter)="save(skills1.value); skills1.value='' " placeholder="skills"></ion-input>
</ion-item>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.