Home > Software engineering >  Which is a better way to access a large object's data members?
Which is a better way to access a large object's data members?

Time:07-01

I have an object in my .ts file consisting of dozen of data members. Now, in order to render them in my html at different places for all different members, shall I reference it from the object directly -

.html

<p>{{obj.m1}}</p>
<p>{{obj.m2}}</p>

OR, I define each variable in .ts file differently - .ts

m1 : string = obj.m1;
m2 : string = obj.m2;

.html

<p>{{m1}}</p>
<p>{{m2}}</p>

I am not sure if it does make a difference.

Thank You!

CodePudding user response:

It's perfectly fine to reference an object property (and its members) of a component from a template.

In order to do that, object property must be public (the default).

Good practice could be also to use Safe navigation operator (?) to avoid any null or undefined value in object member.

<p>The item name is: {{item?.name}}</p>

If item is null, the view still renders but the displayed value is blank; you see only "The item name is:" with nothing after it.

  • Related