Reputation: 2867
I've been searching for questions already posted but none seem to answer this particular case.
Basically, I have a parent component which passes data to the child component. Nothing unusual in the html:
<child-component [dataChild]="dataParent"></child-component>
dataParent
is the result of an http call and it is initialised with a subscriber:
this.myService.myObserver.subscribe(d => {
this.dataParent = d;
});
dataParent
will now be something like this:
{
name: "some random name",
id: 1
}
In the child html this won't throw an error and the object above will be displayed as expected:
<p>{{dataChild | json}}</p>
However, this will:
<p>{{dataChild.name}}</p>
I've seen in other answers that the way some people are dealing with async properties is by using *ngIf. However, I think that's a bit hacky and the problem here is that the error happens only when a property is being accessed.
Am I missing something here?
Upvotes: 1
Views: 620
Reputation: 86720
No need to use *ngIf
as you said in comment you can achive this using elvis operator only, The purpose of the Elvis operator is to allow us to specify bindings where the bound data will become available at a later time. and here in your case also same happened your data is available to component before the binding. so here we use elevis operator only to restrict from throwing error ans when data is availabel to component it is automatically bind to component.
so you can use
<p>{{dataChild?.name}}</p>
for more explanation see here i have created one dummt plunker assuming your use case hope this clears everything.
Upvotes: 2
Reputation: 214007
You could use the Elvis operator like this:
<p>{{dataChild?.name}}</p>
Upvotes: 1