1 javascript firebase ionic3 angular
我想在我的.html代码中将[(ngModel)]分配给一个为空(空或未定义)的对象,但是它给出_co.object为null的错误。 有2种情况,第一种情况是我的对象具有值,第二种情况是没有值。第一种情况ngModel可以正常工作,但是第二种情况下,它给出了为null的错误。我尝试了elvis(?)运算符,但没有帮助。
问题解决了!谢谢你们
我的.ts页面
个人资料:个人资料= {
fullName: '',
email: '',
address: '',
};
Run Code Online (Sandbox Code Playgroud)
我的.html页面
<ion-item>
<ion-label>Full Name:</ion-label>
<ion-input [(ngModel)]="profile.fullName"></ion-input>
</ion-item>
Run Code Online (Sandbox Code Playgroud)
错误TypeError:“ _ co.profile为空”
您始终需要确保获取对象的属性。否则将来您可能会遇到意想不到的问题。
要么使用ngIf
<ion-item *ngIf="profile">
<ion-label>Full Name:</ion-label>
<ion-input [(ngModel)]="profile.fullName"></ion-input>
</ion-item>
Run Code Online (Sandbox Code Playgroud)
或使其可选
<ion-item>
<ion-label>Full Name:</ion-label>
<ion-input [(ngModel)]="profile?.fullName"></ion-input>
</ion-item>
Run Code Online (Sandbox Code Playgroud)
小智 0
感谢你们。我发现我的错误在另一个地方。我以某种方式将ngOnInit中的“配置文件”对象从空重新分配为未定义。就像这样:
ngOnInit(){
//code...
if(!this.profile){
this.profile = {} as Profile; //here was the mistake which I accidentally made.
//and it was assigning my object to null
}
}
Run Code Online (Sandbox Code Playgroud)