Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating an expression from the server with Angular 2

Tags:

angular

I am writing an application where I need to pass an ngIf expression from inside a method. Expression is coming from backend service as string. In Angular 1, I used to use interpolation to evaluate the string before passing to ng-if which then used to get evaluated as true or false, look at plunker below

UPDATED

Plunker Angular 1.5 https://plnkr.co/edit/ukGlJvBZyqGvvrmjEZJY?p=preview

But in Angular 2 , I can not use interpolation with *ngIf, throws exception. Look at the below code. I am expecting none of the lines (Howdy1, Howdy2, Howdy3) appear on UI as passing same expression. But only 1st one is hidden not remaining two where expression is passed as a string variable.

I have plunker code for both Angular 2 and 1.5. If anyone solved similar problem, please help me.

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <h1>Angular 2 Systemjs start</h1>
    <div *ngIf="map['a']=='b' || map['b']=='a'">Howdy1</div>
    <div *ngIf="logicAsString">Howdy2</div>
    <div *ngIf="showDiv(logicAsString)">Howdy3</div>
    <p>{{logicAsString}}</p>
  `
})
export class AppComponent {

  logicAsString:string ="map['a']=='b' || map['b']=='a'";

  map = {
    a:'a',
    b:'b'
  }

  public showDiv(logic){
    return logic; 
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Plunker Angular 2- https://plnkr.co/edit/YExzpE?p=preview

like image 227
Mithun Avatar asked May 31 '26 21:05

Mithun


1 Answers

Using the new Function syntax in JavaScript, you could change your showDiv function to:

public showDiv (logic) {
   let myfunc = new Function ('map', logic);
   let myresult:boolean = myfunc (this.map);
   return myresult;
}

And you'd also have to change the logicAsString to:

logicAsString:string = "if (map['a'] == 'c') return true; return false;"

so it would return the boolean to the caller. This really just wraps your existing logicAsString so you could even do this inside the showDiv function.

And this doesn't use eval, which many people dislike.

Hope it helps!

like image 148
Larry Diamond Avatar answered Jun 03 '26 13:06

Larry Diamond