user2828442
user2828442

Reputation: 2515

How to use ngIf according to a variable's value?

My code in file.html is

<button ion-button item-right>
        <ion-icon name="md-add-circle" (click)="save();"></ion-icon>
      </button>

file.ts

editmode = false;

What I want to achieve is if editmode is false then call save() function, and if editmode is true then call editedu(elem,index) function when button from html page is clicked.

Upvotes: 0

Views: 1562

Answers (3)

Rohan Fating
Rohan Fating

Reputation: 2133

Please see the plunker demo https://plnkr.co/edit/X5e6avkveGeVRqhzLVFr?p=preview

 //our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (click)='editMode = !editMode'>Toggle editMode {{editMode}}</h2>
      <button (click)='editMode? save(): ""'>Call Me</button>
    </div>
  `,
})
export class App {
  name:string
  editMode: boolean = true;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  save(): void {
    alert("Called because editMode is true");
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

Juse use

<button ion-button item-right>
 <div *ngIf="editmode">     
<ion-icon name="md-add-circle" (click)="editedu(elem,index);"></ion-icon>
</div>
 <div *ngIf="!editmode">     
<ion-icon name="md-add-circle" (click)="save();"></ion-icon>
</div>
</button>

if you want to do it in single line,

<div   *ngIf=editmode ? save() : editedu(elem, index)">
   <ion-icon name="md-add-circle" (click)="save();"></ion-icon>
</div>

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

You can use ternary if (or you can call a method where you call another method depending on editmode)

(click)="editmode ? save() : editedu(elem, index)"

Upvotes: 1

Related Questions