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

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

angular - Remove ngIf item on dual conditions

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...