15

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
yurzui
  • 205,937
  • 32
  • 433
  • 399
RiceRiceBaby
  • 1,546
  • 4
  • 16
  • 30

4 Answers4

17

? 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".

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • 1
    `?.` short-circuits. (If `product` doesn't exist, the expression evaluates to null and `product.id` is never evaluated.) It shouldn't throw an error unless `product` exists and `product.id` doesn't. – cHao Aug 01 '18 at 15:45
15

Literally this means:

((product == null) ? null: product.id.name)

So if product is null then return null otherwise return the whole value.

enter image description here

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:

yurzui
  • 205,937
  • 32
  • 433
  • 399
4

Just syntaxic sugar for product && product.id.name

Guerric P
  • 30,447
  • 6
  • 48
  • 86
3

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 
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91