Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from an *ngIf Angular 5

Say I have this code here

<div *ngIf="item">lorem ipsum</div>

Is there a way I can call a function if that *ngIf evaluates to true??

you know something like this..

<div *ngIf="(item) : callFunction() ? ...">lorem ipsum</div>

any help would be appreciated!

Thanks

like image 333
Smokey Dawson Avatar asked Apr 04 '18 03:04

Smokey Dawson


People also ask

Can we call a function in ngIf in Angular?

Try *ngIf="condition && yourfunction()" . Your function must return true to the if evaluate to true, but it will only be executed if your condition is true, since an and operator will stop on first false. I would advise against this. This is very bad practice and will cause serious performance issues in your codebase.

Can we use method in ngIf?

It can be a property of the component class. It can be a method in the component class. But it must evaluate to true/false. The ngIf directive tries to coerce the value to Boolean.

What is * ngIf in Angular?

A shorthand form of the directive, *ngIf="condition" , is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.


3 Answers

Angular way would be:

<div *ngIf="name; then func(); else false">;</div>

But as *ngIf evaluates passed in logical expression, you can also do:

<div *ngIf="name?func():false">;</div>

like image 119
Julius Dzidzevičius Avatar answered Oct 12 '22 13:10

Julius Dzidzevičius


Try like this

<div *ngIf="item ===true?callFunction():'otherStuff'">lorem ipsum</div>
like image 41
brk Avatar answered Oct 12 '22 14:10

brk


You can try like this

Html

<div *ngIf="item; then callfunction; else nofunction"></div>
<ng-template #callfunction>
  {{call()}}
</ng-template>
<ng-template #nofunction>
 <!-- something else -->
</ng-template>

Ts

call(){
}

If you got better solution than this please post that to

like image 20
Abinesh Joyel Avatar answered Oct 12 '22 14:10

Abinesh Joyel