What is the exact difference between ?. and ?: operators in angular
So there is a difference when using the ? within Angular, here are the three ways you may be referring to for the usage.
safe-operators
When you set a value within the HTML with a question mark in it, this is a safe check, so you check the variable is defined before you access it. (trying at access values the do not exist will result in errors).
The snippet below would check this.example
has a value before checking for text which would result in an error. If text is accessed while undefined this can almost assure unwanted behavior.
<p>{{example?.text}}</p>
This keeps everything safe, to read more about safe operators, have a read through the Angular docs found here
Optional Parameters
The next use which is what I think you were looking for is optional values in functions / interface. This means that the interface will not throw an error if it is called without the exampleValue
as it has now been defined as optional.
export interface Itest
{
exampleValue?: string; // optional
neededValue: string; // non-optional
}
Or within a function, without the optional indicator (?
) an error would occur if the function was called like. this.exampleFunction();
public exampleFunction(test?): void
{
console.log(test);
// this function can be called with or without test being passed in without causing an error.
}
More examples of this can be found in this short article about Optional Parameters
Conditional (ternary) operator
The question was not looking for this but thought it would make sense to pop it in as its another case where the ?
can be seen in use.
When seen in typescript you can use it in a conditional ternary statement (if / else)
looking like so.
const example = 'hello';
console.log(example === 'hello' ? 'im true' : 'im false');
which would be the same as writing the following statement.
const example = "hello";
if (example === 'hello')
{
console.log('im true');
}else
{
console.log('im false');
}
More information and uses of the Conditional (ternary) operator can be found here.
?.
is a safe-navigation operator. It simply makes it so no errors will be thrown if the preceding value is null. There are some nitty-gritty details at play, but it can basically be thought of as a null-checking ternary expression.
<div>{{item?.value}}</div>
... is roughly the same as:
<div>{{item ? item.value : null}}</div>