Mark
Mark

Reputation: 171

How to change the event at the press of a button in angular 6?

everyone. I just started to learn Angular 6 and I have a question. I need that when a button is pressed, not only does the text of the button change, but the event changes, which should occur when the button is pressed. For example, the first click on the button will add the component to the memory, and the second click on this button will delete.

Here is my code from HTML:

<button class="btn" (click)="toggleEvent()">
        {{addToMemory ? 'Add to memory' : 'Delete from memory'}}
</button>

From TS:

addToMemory: boolean = true;

toggleEvent(): void {
 this.addToMemory = !this.addToMemory;
}

I have a function that will add the film to memory and delete.

add() {}
delete() {}

But I don’t understand how to switch a button by clicking between these functions. Please explain and help. Examples that I have found or do not work or it is not clear how to apply them. Sorry for my bad english.

Upvotes: 1

Views: 2526

Answers (2)

SeleM
SeleM

Reputation: 9638

Your HTML part:

<button class="btn" (click)="toggleEvent()">
        {{addToMemoryFlag ? 'Add to memory' : 'Delete from memory'}}
</button>

Your TS part:

addToMemoryFlag: boolean = true;

toggleEvent() {

   this.addToMemoryFlag = !this.addToMemoryFlag;

   if(this.addToMemoryFlag) {
       this.addToMemory();
   } else {
       this.deleteFromMemory();
   }
}

It is better better to differentiate names between addToMemory variable and addToMemory() method, change either the variable or the method's name.

Upvotes: 1

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

Template:

<button class="btn" (click)="toggleEvent()">
        {{addToMemory ? 'Add to memory' : 'Delete from memory'}}
</button>

Component:

    addToMemory: boolean = true;

    toggleEvent(evt){
    this.addToMemory = !this.addToMemory;
    switch(evt.target.innerHTML.trim()){
      case 'Add to memory':
          this.Addtomemory();
          break;
      case 'Delete from memory':
          this.DeleteFrommemory();
          break;
    }
  }

Upvotes: 0

Related Questions