Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to call the method onRemoveLastTag() with dual conditions. I want to call the method only when the form is empty and keyup.backspace.

Backspace should operate normally while there is still text in the input field. This is an Angular 11 application.

<form [formGroup]="searchForm">
  <label for="search"></label>
  <span class="chippie"
        *ngFor="let tag of selectedTags; let i=index">
    {{tag}}
    <a class="close"
       (click)="onRemoveTag(i)"
    > X</a></span>

  <input
    id="search"
    formControlName="search"
    type="text"
    placeholder="Your tag goes here"
    class="form-control"
    autocomplete="off"
    (keyup.enter)="addTag($event)"
    (keyup.backspace)="onRemoveLastTag()"
    (keyup)="openDropdown()"
    (keyup.arrowLeft)="toggleDropdown()"
    >
</form>
onRemoveLastTag() {
  this.selectedTags.pop();
  console.log(this.selectedTags)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem here was that I tried to build logic into the HTML. I believe it's best practice to keep the logic in TypeScript. Here is the method I used to handle the logic.

onBackspace() {
  if (!this.getSearchValue()) {
    if (!this.isSelectingAndRemovingTags) {
      this.isSelectingAndRemovingTags = true;
      return;
    }
    if (this.toBeRemovedTagIndex < 0) {
      this.toBeRemovedTagIndex = this.selectedTags.length - 1;
      return;
    }
    this.onRemoveTag(this.toBeRemovedTagIndex);
    this.toBeRemovedTagIndex = this.selectedTags.length - 1;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...