My template is trying to reference a property of a model, like so: {{someModel.propertyName}}
. The value of the model is passed by the outer component, so it is defined like this: @Input() someModel: someModelInterface = new SomeModel();
. The outer component gets this model asynchronously, using Observable.
I am getting an error, that template can not display property propertyName
of undefined
.
I get this error even if I create an empty instance of the model in the constructor.
I understand why this is happening: at the time that the template is trying to render the property of the model, the model is not passed, yet. I was able to solve this by adding the ?
in the panel {{someModel?.propertyName}}
but this does not look like a clean solution, more like a workaround. Is there a better way?
Also, why does template see it as undefined even though I create it in the constructor?
Asked
Active
Viewed 33 times
0

Joseph Genchik
- 1,821
- 3
- 15
- 19
1 Answers
0
Use
{{someModel?.propertyName}}
This way Angular doesn't throw if someModel
is still null when it tries to bind propertyName
.
?.
is the safe navigation operator (Elvis operator) which returns null
if the part before ?.
is null
and doesn't even try to access propertyName
as long as someModel
is null
.

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567
-
Thank you. I understand what you are saying, but it seems that there should be a better way. Also, why doesn't template "see" the model if I am creating it in the constructor and when it is defined? – Joseph Genchik Mar 09 '16 at 18:56
-
You said you are fetching it asynchronuosly, or did I misinterpret something? – Günter Zöchbauer Mar 09 '16 at 18:59
-
Sorry, I missed that you already use `?.` as workaround. This is the right way to do it anyway. – Günter Zöchbauer Mar 09 '16 at 19:03