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