I know the if I have something like product.id == 1 ? stuff : not stuff. That means if id = 1, then choose "stuff". If not, then choose "not stuff". What does the following mean:
product?.id.name
I know the if I have something like product.id == 1 ? stuff : not stuff. That means if id = 1, then choose "stuff". If not, then choose "not stuff". What does the following mean:
product?.id.name
?
Means safe navigation operator
From Docs
The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.
This specifically means that if the value you are binding to the view is null then it should return null else the actual value, so that you dont get any issues while rendering the template.
In the above sample code you provided ,
product?.id.name
it checks whether produce object exists and then it will check if there is an id.
since you dont have ?
after id. it will throw an error "cannot read property of 'name' undefined".
Literally this means:
((product == null) ? null: product.id.name)
So if product
is null then return null
otherwise return the whole value.
If we have:
product?.id?.name
then we should expect something like:
((product == null) ? null: ((product.id == null) ? null: product.id.name))
If you're doubt then you can always check how it looks like after angular compiler:
For more details see docs:
Angular safe navigation operator (?.) prevent to navigate throw null or undefined component property
let assume you have a property in you component named person
and it null
or undefined
{{person.name}} // in case of null Uncaught TypeError: Cannot read property 'name' of null
{{person?.name}} // working fine