skip to Main Content

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


  1. For this you should create a EveryPipe for that.

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

    used like following

    <div *ngIf="(myObj | every:null)"> 
       ...
    </div>
    
    Login or Signup to reply.
  2. 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:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-my-component',
      templateUrl: './my-component.component.html',
    })
    export class MyComponent {
      myObj = { key1: null, key2: null, key3: null };
    
      hasOnlyNullValues(obj: any): boolean {
        return Object.values(obj).every(x => x === null);
      }
    }
    

    In your template HTML:

    <div *ngIf="hasOnlyNullValues(myObj)">
      The object contains only null values.
    </div>
    <div *ngIf="!hasOnlyNullValues(myObj)">
      The object contains non-null values.
    </div>
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search