Nimit Joshi
Nimit Joshi

Reputation: 1046

How to call button click event before blur using angular 6

In my page i have two controls: textarea and button.

Scenario: Whenever user clicks outside of the textarea i have to save the value of textarea. If user clicks in cancel icon the data will not be saved. For this i have used the following code:

<textarea id="sht-edt-{{Index}}-{{RecordIndex}}" autofocus kendoTextArea                                    
 (blur)="Save(Record.Model)" [autoSize]="true"
 #Model="ngModel" [required]="Required" [(ngModel)]="Record.Model"></textarea>

<button ng-mousedown="CloseEditMode(Index, RecordIndex)"><span class="icon-cross"></span></button>

I have used events like: click, ng-mousedown and mousedown but it is always calling the Save method of textarea. How can i call CloseEditMode() method before Save() method?

Upvotes: 1

Views: 797

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21638

As you are using the blur event to save it is always going to be called before any other event when you click outside the textarea. If you want to have blur save automatically but the cancel button cancel the save you will need to add a timeout to the save. Try 100 or 200 milliseconds for the timeoutPeriod.

cancelled = false;

Save(model) {
  setTimeout(() => {
    if (!this.cancelled) {
      // save logic
    } else {
      // Close the modal
    }
  }, timeoutPeriod);
}

and set cancelled on the cancel button

<button (click)="cancel = true"><span class="icon-cross">

Make sure to set cancelled back to false on focus

<textarea  (blur)="Save(Record.Model)" (focus)="cancelled = false"

Here is a StackBlitz https://stackblitz.com/edit/angular-ecevqn

Upvotes: 1

Vaibhav More
Vaibhav More

Reputation: 3

Disclaimer : I am not an expert in angular.js.

When you click on cancel button

  • Text area loses focus. Hence the save method will be called
  • CloseEditMode will be called

If you want to shift the priorities of the event call either

  • Create a Save button which records the data
  • Save method has a callback to CloseEditMode

I hope this helps

Upvotes: 0

Related Questions