0

I am new to the front end development and I am self learning Angular (11.2.10). I came across this piece of in a sample project in the html template written by someone else and is used at bunch of places:

<div #itemsList [currentItemId]="item?.id"></div>

I am wondering for what ?. is used for here? I want to learn more about it. Even I am not sure if it is part of TS or Angular?

What should I search for to learn about this expression in the official documentation of Angular/TS?

May be I have not covered that topic yet in my learning yet. Any information in this regard will be greatly appreciated.

Update:

Based on answers by polyglot and liyaxing I found what I looking for - Optional Chaining

Also, similar question was asked here too

Safe navigation operator (?.) or (!.) and null property paths

But since I didn't know what I was looking for, I wish not to delete this question.

Ajay Kumar
  • 2,906
  • 3
  • 23
  • 46

2 Answers2

1

The question mark is used to mark the TypeScript variable as optional. This is to avoid TypeError: Cannot read property 'item' of null if the variable item is null. So in the case that item is null or undefined, "item?.id" will return undefined instead of throwing an error.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

liyaxing
  • 69
  • 4
  • so what should I "google" for to learn more about it? As I mentioned in the original question I want to learn it all. - `Type Script Optional` ? – Ajay Kumar Apr 22 '21 at 02:27
  • You can search for "Type Script Optional Parameters". You can find resources like https://www.typescriptlang.org/docs/handbook/2/functions.html#optional-parameters – liyaxing Apr 22 '21 at 02:36
  • 1
    This answer isn't quite correct in this context. `?` does mark a property as optional, but that's not what's happening here. Here, you are accessing a property that's already optional, and doing it in a `null`ish-safe way. – Noah Apr 22 '21 at 02:39
  • 2
    It's optional chaining https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html – maxhuang Apr 22 '21 at 02:39
1

It's a kind of ternary operator in Typescript such that if object item exists and contains id property, then item.id is picked up; otherwise, null is picked up. It's used when the object is nullable. Therefore your code is identical to the following:

<div #itemsList [currentItemId]="item? item.id : null"></div>

polyglot
  • 822
  • 5
  • 9