Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function if *ngIf is true? [duplicate]

Tags:

angular

ionic2

Here I have an ion-input which I want to hide only when item.type==2 in the list of items

<ion-input type="text"></ion-input>

<div *ngFor="let item of items">
  <div *ngIf="item.type == 2">
    <span>The End</span>
  </div>
</div>

How should I go about this ?

like image 475
Sai Datta Avatar asked Aug 25 '17 14:08

Sai Datta


People also ask

How do you call a function after ngIf?

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 two conditions in ngIf?

We can use multiple conditions in *ngIf with logical operator AND (&&) to decide the trustworthy of *ngIf expression. If all conditions are true, then element will be added to the DOM.

What is * in * ngIf?

The * syntax means that ngIf is a structural directive, meaning that it affects the structure of the page.

What is * ngIf and how does it work?

NgIflink. A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause.


1 Answers

<ion-input type="text"></ion-input>

<div *ngFor="let item of items">
  <div *ngIf="check(item)">
    <span>The End</span>
  </div>
</div>


export class YourCom{

   check(item){
       if(item.type == 2){

          callThatFunction();
       }

   }
}

This is a better practice anyway, that makes your check function testable, which is your business logic.

but don't forget that if you call a function that updates the view somehow, you're gonna get an error from change detection that says >"Expression updated after view is checked"

like image 192
Milad Avatar answered Sep 20 '22 10:09

Milad