What is meaning for question mask after variable name in html


#1

I am learning ionic, and notice that some code has the variable

in ts file
foo: Reference

then in html , it will be used like
*ngIf="foo?.bar

why there is a question mask? how to use it?


#2

This is the safe navigation operator. It allows you to attempt to access a property of an object without causing an error if it does not exist. For example if you have a user object and attempt to access:

{{user.name}}

in a template, that will work fine as long as user is defined and it has a name property. However, user might be undefined when the template attempts to access it and this will trigger an error because there is no name property on undefined. If you use:

{{user?.name}}

It won’t trigger an error.


#3

My opinion is that it shouldn’t be used. Templates should not have to worry about this: it should be the responsibility of the controller to always have object and array properties in a sane (if empty) state.


#4

I believe its called the elvis operator, right? And yeah, I’m in agreement with @rapropos that it shouldn’t be used.

It should be the controller that lays a foundation for your template in a way that makes this tactic unnecessary. At least, it’s a bad habit that doesn’t lend itself to good programming, at worst it masks a potential landslide of errors.


#5

My humble advice is never use it. Just ensure that you initialize your items’ (in this case user) properties in your constructor. I.e.,

this.user = {
 name: "",
 age: null
 }

Etc.


#6

I have found setting "strict": true in tsconfig.json to be quite helpful (along with noImplicitAny). It would flag at build time any property that is not initialized either at declaration point or in a constructor, unless you use the ! definite assignment operator upon declaration or explicitly add null or undefined as a union of the property type.


#7

I’m guessing that flags you for using any as a type when declaring class properties, not assigning a type to function params, or both?

This is great. I’ve picked up a lot of great advice on this forum especially when I was just starting off. Not using any, anywhere at any time was the most beneficial of that advice on a fundamental level.

It improved readability, helped me to understand the syntax I was using on a much deeper level and was a jumping off point for moving from total hack to decent programmer.


#8

Explicitly declaring something as any is allowed, but it will flag properties, function arguments and return values that have no type declaration at all. For migration convenience, those are silently treated as any normally.