5

I have the form with async data:

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

It works only if I add *ngIf="currentService.user" to the form, but I want to render inputs without value before I get data from the server. But I get the following error:

'Cannot read property 'username' of undefined'

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

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Volodymyr Humeniuk
  • 3,411
  • 9
  • 35
  • 70
  • What are you trying to achieve here ? If there is already a user then fill the inputs with that and if not just bind to the empty user ? If so, what do you want to show until the current user is retrieved ? – CornelC May 17 '18 at 11:15
  • try using this `` – Sanoj_V May 17 '18 at 11:21
  • How do you retrieve the user? You could update your FormControl when the data is acquired. – TomVW May 17 '18 at 11:44
  • 1
    You can see a solution in [this answer](https://stackoverflow.com/a/36016472/1009922): use the [safe navigation operator](https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths) in `[ngModel]` and set the value in `(ngModelChange)`. – ConnorsFan May 17 '18 at 11:46

3 Answers3

5

You could Try this out

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

Working Example

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • I am surprised to see that this does indeed work. I tought that it was not a valid syntax, since we cannot assign a value to `currentService.user && currentService.user.username`. – ConnorsFan May 17 '18 at 12:19
  • 1
    Awesome!! This saved my day!. Thanks! – javatar Jan 04 '19 at 11:26
1

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;
ochs.tobi
  • 3,214
  • 7
  • 31
  • 52
1

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>
Sujan Gainju
  • 4,273
  • 2
  • 14
  • 34