问题
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