0

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?

mxcx
  • 75
  • 8

2 Answers2

3

For this you should create a EveryPipe for that.

@Pipe({ name: 'every' })
export class ContainsPipe implements PipeTransform {
   transform(input: any, value: any): boolean {
      return Object.values(input).every(x => x == value)
   }
}

used like following

<div *ngIf="(myObj | every:null)"> 
   ...
</div>
mxcx
  • 75
  • 8
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
0

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 variable x in order to verify if there are any values equal to null.

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:

<div *ngIf="containsOnlyNullValues(myObj)">
  // content to be conditionally displayed goes here ...
</div>

.ts:

public containsOnlyNullValues(myObj: any) {
  return Object.values(myObj).some(x => x !== null);
}

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.

Karel
  • 79
  • 1
  • 5