Async data in ngModel

只愿长相守 提交于 2019-12-12 13:23:46

问题


I have form with async data binded from server:

<form>
 <input [(ngModel)]="currentService.user.username">
 <input [(ngModel)]="currentService.user.email">
</form>

It's work only if i add *ngIf="currentService.user" to form, but i want render inputs without value, before i get data from server. But i get errors:

'Cannot read property 'username' of undefined'

How can i solve this? Probably, i need something like async pipe to ngModel, but this is does not work, obviously.


回答1:


You could Try this out

 <input [(ngModel)]="currentService.user && currentService.user.username">
 <input [(ngModel)]="currentService.user && currentService.user.email">

Working Example




回答2:


You need to initialize the user in your service. I think your code looks like this:

private user: User;

and then later you make a HTTP call or something like that to set the user. But at the time the user is retrieved the user is undefined until the async call is finished.

So if you change your line like this it should work:

private user: User = new User;



回答3:


You have to define currentService as a object as below then you can use it before you get the data from the server.

currentService = {
    user : {
        username: '',
        email: ''
    }
}

then

<form>
 <input [(ngModel)]="currentService.user.username">
 <input [(ngModel)]="currentService.user.email">
</form>


来源:https://stackoverflow.com/questions/50389639/async-data-in-ngmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!