Angular’s NG8107 error is a type of error that occurs when you try to use a non-existent property or method on a component. It’s commonly caused by a typo or mistake in the component’s template, where a property or method that doesn’t exist is referenced.
The warning signifies that if it is known that the left side of an optional chain operation will not be null or undefined, then the ‘?.’ operator can be replaced with the ‘.’ operator, which will not throw an error if the left side is null or undefined. This can improve code efficiency and eliminate unnecessary null checks.
Fix for warning NG8107: The left side of this optional chain operation does not include ‘null’ or ‘undefined’ in its type, therefore the ‘?.’ operator can be replaced with the ‘.’ operator
To resolve the warning NG8107, replace the ‘?.’ operator on the left side of the optional chain operation with the ‘.’ operator. Because the left side of the operation is known not to be null or undefined, using the ‘.’ operator does not result in an error.
For instance, suppose you have the following code:
let myVariable = myObject?.myProperty;
The code is using the optional chaining operator (?) in TypeScript, which allows you to use the value of a property within an expression that’s assigning the value of another property. Above, If myObject is defined and myObject.myProperty exists, then myVariable will be assigned the value of myObject.myProperty. If myObject is null or undefined, or if myObject.myProperty does not exist, then myVariable will be assigned the value undefined .
The fix is to change that to:
let myVariable = myObject.myProperty;
In the following example, it’s assumed that myObject has been previously defined and that it has a property named
myProperty. If myObject is undefined or if myObject does not have a property named
myProperty, then the code will throw an exception.
Above, if it is known that myObject.myProperty is not null then we can avoid the ‘? ‘operator. This avoids the NG8107 warning while also making the code more efficient and avoiding unnecessary null checks.