Cannot pass condition as boolean in Angular

I want to try to pass a condition in a string clause because these parameters are in the target component:

source.component:

export class TestComponent implements OnInit {
  condition: boolean;

  ngOnInit() {
    this.condition = !"element.id === 2";
  }
}

However, I cannot use this condition in the target component:

target.component:

@Input() condition;


<button *ngIf="!condition" mat-menu-item (click)="openDialog(element)">Edit</button>

Here is the demo for this problem:

DEMO

Why I do not add these parameters manually to the target component is that; it is reusable component and the conditions may be different for another component. So, how can I pass condition from another component?

just have a look at <button *ngIf="element.id % 2 === 0" mat-menu-item (click)="openDialog(element)">Edit</button>. Instead of setting *ngIf="element.id % 2 === 0, I need to pass element.id % 2 === 0part from another component e.g. condition:‘element.id % 2 === 0’. Then I need to get that option via @Input` in this component. But I receive it as string and when I convert it it always returns true 🙁

3 thoughts on “Cannot pass condition as boolean in Angular”

  1. You can use javascript eval function to convert your string into evaluated expression

    target.component:

    ngOnInit(){
       this.condition = eval(this.condition) // this will convert your string into evaluated `expression`
    }
    
    Reply
  2. For this you need to understand how angular resolves expression as string,

    it internally uses eval('expression as string')

    I did changed the on init as following

    Source Component :

    export class TestComponent implements OnInit {
      condition: boolean;
    
      ngOnInit() {
        this.condition = "eval('!(element.id === 2)')";
      }
    }
    

    here’s the working link :
    Working Demo link

    Reply

Leave a Comment