![](/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.