I can check if the object itself is null
with (myObj | keyvalue)?.length
. (https://stackoverflow.com/a/56532650/13797956)
With JS I can check if the object contains only null
values with Object.values(myObj).some(x => x !== null)
.
But when I try to use this in the template I get Parser Error: Bindings cannot contain assignments
.
Is there a way to check if myObj
only contains null
values inside the template or should I use a function that does the work?
3
Answers
For this you should create a
EveryPipe
for that.used like following
In Angular templates, you cannot directly use expressions with assignments or complex logic. Therefore, you’ll need to create a function in your component to perform the null value check and then call that function in your template. Here’s an example of how you can achieve this:
In your component TypeScript code:
In your template HTML:
The error says it all. The template parser can not assign values to variables. But you are assigning the values of
myObj
to a local variablex
in order to verify if there are any values equal tonull
.You will have to create a method on the component or use a pipe to achieve what you want. For example, with a function:
.html
:.ts
:Note that you can store the value of a conditional result as a variable which can be used later on in the template. But that is the only exception to this rule.