Search code examples
angulartypescriptng-tags-input

How to not remove the tag input chip when hitting the last backspace?


I am using the tag input created in Angular. The problem which I am facing is that whenever I hit backspace for the last character, it removes the previous tag as well.

example

I don't to remove the previous tag as soon as the input is empty, I want to to remove when the user hits backspace for the second time. For Example in Gmail when we compose a new email and send to multiple email Ids.

This is happening because of the following code :

if (event.code === 'Backspace' && !inputValue) {
      this.removeTag();
      return;
}

I have tried a lot of things but couldn't fix this bug.

Here is a stackblitz link for it : Stackblitz Link

How should I solve it?


Solution

  • You can use keydown instead of keyup.

    To explain more, the native input element will remove the character at the pointer when the backspace key is pressed (keydown). after that your logic is being triggered (keyup). At that point the previous character in the input field is part of the previous chip, that is why it is being removed.