user8770372
user8770372

Reputation:

Angular 2+ Creating a Toggle of 2 different cases

I am trying to create a toggle in angular 4 calling a function when the click event is called.

<button (click)="toggle()">Toggle Button</button>

And then in the .ts file I want something like this:

toggle() {

    alert('toggle case 1') 

    else

    alert('toggle case 2');

}

Basically I want to have 2 different actions...how do I do this?

Upvotes: 1

Views: 3484

Answers (3)

UncleDave
UncleDave

Reputation: 7188

If you just need to toggle a simple boolean you can do the following:

<button (click)="toggle()">Toggle Button</button>

class MyComponent {
  isToggled: boolean;

  toggle() {
    this.isToggled = !this.isToggled;
  }
}

Then you can use isToggled in your view, if needed.

For something more complicated you can expand your toggle() method like so:

toggle() {
  this.isToggled = !this.isToggled;

  if (this.isToggled) {
    // do something, we've just been toggled on
  } else {
    // do something else, we've just been toggled off
  }
}

Upvotes: 1

Vivek Doshi
Vivek Doshi

Reputation: 58553

Your Template

<button (click)="toggle()">Toggle Button</button>

.ts file

button_clicked = false;

toggle() {
    this.button_clicked = !this.button_clicked;
    if(this.button_clicked) 
    { 
        // call function 1 
    } 
    else 
    { 
        // call function 2
    }
}

Upvotes: 0

Gili Yaniv
Gili Yaniv

Reputation: 3211

You should declare a Boolean in your component and act by its value.

<button (click)="toggle()">Toggle Button</button>

toggleFlag:boolean=false;

toggle() {
    this.toggleFlag=!this.toggleFlag;
    if(this.toggleFlag)
       alert('toggle case 1')     
    else
       alert('toggle case 2');
}

Upvotes: 0

Related Questions