admin管理员组

文章数量:1204600

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

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

Share Improve this question asked Apr 4, 2018 at 3:23 Smokey DawsonSmokey Dawson 9,23021 gold badges85 silver badges161 bronze badges 4
  • 1 Does this help? angular.io/api/common/… – Isaac Commented Apr 4, 2018 at 3:27
  • 3 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. – Elias Soares Commented Apr 4, 2018 at 3:28
  • 1 Can you give some more context of what you are trying to do? Otherwise the answer is to just add a check to ngOnCheck – Pace Commented Apr 4, 2018 at 3:28
  • 3 I would advise against this. This is very bad practice and will cause serious performance issues in your codebase. Instead use a Boolean variable in your templates. Calling a method will result in multiple calls, every time change detection occurs. In one of my apps, it called the method over 4,000 times, before resolving: medium.com/showpad-engineering/… – Charles Robertson Commented Feb 18, 2022 at 21:42
Add a comment  | 

3 Answers 3

Reset to default 13

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>

Try like this

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

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

本文标签: javascriptCall a function from an *ngIf Angular 5Stack Overflow