Search code examples
javascriptangularangular-ng-if

Angular ngIF: take variable value as condition


I'm trying to bind inputs from the back side to the front and got a question: to avoid crazy parsing exercise, can I use an income variable as a condition for *ngIf instruction? Like this:

    <div *ngFor="let ban of banners">
        <div *ngIf="ban.view_condition">
            <a [href]="ban.url" target="_blank">
                <img [src]="ban.img_url" [alt]="ban.title">
            </a>
        </div>
    </div>

In ban.view_condition I'm trying to pass something like: "(parameterN == true || size > 5)"

So the idea is to pass from the backend the set of properties that I want to check and based on this result - display or not the banner. Main goal - avoid manual validation.

Example: (that's what I reveive from back) ban.view_condition = "app.size==10||userName=='test'";

Basically I want to take the value and get something like: *ngIf="app.size==10||userName=='test'" in the end.

Is it feasible? Of course, I understand that all targeted properties need to be present in the component. Thanks for any inputs or ideas!


Solution

  • I would recommend creating a function in the controller that determines whether the banner should be displayed.

    However, if you still want to evaluate that string as actual code. You may use the eval function.

    evaluate(condition: string) {
        // eval(condition) will evaluate javascript code and execute it.
        return eval(condition);
    }
    

    Also, you must ensure any properties in the condition actually exist. (valid javascript)

    I would still argue this is not the best approach, and you should reconsider your design.