So i have a complex date model coming from the server to feed my Angular2 component. Following shows a small part of the template for this component:
<div>
<span>{{Person.Address.City}}</span>
<input type="text" [(ngModel)]="Person.Address.City" />
</div>
The Address
might be null
or undefined
depending on the data that's returned from the server. I know that elvis operator will save me from one error:
<span>{{Person?.Address?.City}}</span>
but unfortuantely it won't save me for [(ngModel)]="Person.Address.City"
as there is no elvis defined for that. You'll get a parser error if you do something like [(ngModel)]="Person?.Address?.City"
and if you don't then you'll get the null
exception.
Here are two simplest variation of data, although there can be a lot more:
{
Name:'sam',
LastName: 'jones',
Address: {
Street: '123 somewhere',
City: 'some land'
State: 'SL'
}
}
or...
{
Name:'sam',
LastName: 'jones'
}
Since the responsibility of handling these scenarios should be on Angular2 rather than the server that provides the data, due to separation of presentation and business logic, how would I handle the scenario(s)?
So as it turns out, you either maintain 3 models, one for front-end (Angular2), one for middle tier (ASP.NET, JAVA, etc...) and another for your data model. Or you could make sure, as i did, that your middle-tier model will not have a null complex object. This means initializing complex properties inside your model and getting away with 2 models.
Also to note, if you have don't or can't modify your middle-tier model, then your only option is to create a compatible model for your front-end (Angular2) and merge as necessary once data has returned from API, service, etc..