0

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?

Joseph Genchik
  • 1,821
  • 3
  • 15
  • 19

1 Answers1

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