i’m running a local server with json-server where i get my mockup data from.
I want to load data in my app.html like this:
Welkom
i’m running a local server with json-server where i get my mockup data from.
I want to load data in my app.html like this:
Welkom
user.firstname
is called before user
is defined. You can do any of the following:
{{ user ? user.firstname : null }}
<ng-container *ngIf="user">
{{ user.firstname }}
</ng-container>
class AppComponent {
public user = {};
}
I’d personally go with the ng-container
Thank you so much!
Why is it beter to go with the ng-container? i’m new to this
Even better to populate the user objecr with empty data so u dont need to test
public user = {firstname:''};
Do this in the constructor or when declaring the variable in the class
And angular allows this in template to dodge issues. Easier then the suggested elvis
{{user?.firstname}}
Just personal preference, really. It looks better than {{ user ? user.firstname : null }}
and I’m not a fan of pre-populating a property unless necessary.
Latest suggestion from @Tommertom is probably the most ideal one!
Indeed matter of opinion
I go for pre populating to keep code simple and demonstrate control of data
So how does that work?
this goes in my class: user: any;
then in my constructor i have: this.getUser(); after this.initializeApp();
And this is my function:
getUser(){
this.restProvider.getUser()
.then(data =>{
this.user = data;
});
}
Where should i place the empty object?
*i switched accounts…
Thank you @mich356c and @Tommertom for your help!
If that is the approach you wish to use:
user: any;
-> user: any = {};
Though keep in mind, if you then use nested properties like {{ user.likes.cake }}
in your template, it will throw the same error as before, since it’s trying to read cake
of likes
which is undefined
.
You can nest the Elvis operator ({{ user?.likes?.cake }}
), but then it just starts looking messy too
yes, this fix my code, tks…