Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async data in ngModel

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.

like image 225
Vladimir Humeniuk Avatar asked May 17 '18 10:05

Vladimir Humeniuk


People also ask

What is asynchronous data in angular?

An asynchronous data stream is a stream of data where values are emitted, one after another, with a delay between them. The word asynchronous means that the data emitted can appear anywhere in time, after one second or even after two minutes, for example.

Can we call function in ngModel?

Yeah, you can use a function.

What does [( ngModel )] mean?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.

What should I import into ngModel?

To use NgModel we need to import FormsModule and add it to imports attribute of @NgModule in our module file.


3 Answers

You could Try this out

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

Working Example

like image 96
Pardeep Jain Avatar answered Sep 21 '22 00:09

Pardeep Jain


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;
like image 38
ochs.tobi Avatar answered Sep 18 '22 00:09

ochs.tobi


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>
like image 32
suzan Avatar answered Sep 20 '22 00:09

suzan