Call function on condition in Angular 2

2019-09-11 01:39发布

问题:

I have template like this

 <div class="action" *ngFor="let action of (actions | async)">
          <div
            class="collapsible action-table-row"
            [attr.aria-expanded]="actionCollapse.isActive()"
            [class.collapse-table-row]="actionCollapse.isActive()"
            (click)="openActionCollapse(actionCollapse)"

          >

I want to call a function if condition satisfied, something like this

 <div class="action" *ngFor="let action of (actions | async)">
          <div
            class="collapsible action-table-row"
            [attr.aria-expanded]="actionCollapse.isActive()"
            [class.collapse-table-row]="actionCollapse.isActive()"
            (click)="openActionCollapse(actionCollapse)"
            (action.value=="")="callfunction()" //<---- here
          >

How can I achieve this.

回答1:

<div class="action" *ngFor="let action of (actions | async)">
          <div
            class="collapsible action-table-row"
            [attr.aria-expanded]="actionCollapse.isActive()"
            [class.collapse-table-row]="actionCollapse.isActive()"
            (click)="openActionCollapse(actionCollapse)">

         {{ action.value=="something" ? callfunction() : '' }} //<---- here

</div>

Recommended way:

<div class="action" *ngFor="let action of (actions | async)">
          <div
            class="collapsible action-table-row"
            [attr.aria-expanded]="actionCollapse.isActive()"
            [class.collapse-table-row]="actionCollapse.isActive()"
            (click)="openActionCollapse(actionCollapse)">

        {{ action.value=="something" ? someVar : '' }} //<---- here

</div>

constructor(){
     this.someVar=this.callfunction();
}

callfunction()
{
   return "something";
}