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.
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.
Yeah, you can use a function.
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.
To use NgModel we need to import FormsModule and add it to imports attribute of @NgModule in our module file.
You could Try this out
<input [(ngModel)]="currentService.user && currentService.user.username">
<input [(ngModel)]="currentService.user && currentService.user.email">
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;
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With