如何停止在自动完成组件中添加重复的芯片?

问题描述 投票:0回答:5

如何停止使用 Angular Material 芯片在列表中添加重复值?例如,我想在水果列表中只添加苹果一种,当我添加柠檬时我也想只添加一种。现在我可以多次添加。当我关闭芯片时,我希望能够再次添加它。我将不胜感激任何帮助。谢谢!

import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent, MatChipInputEvent} from '@angular/material';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

/**
 * @title Chips Autocomplete
 */
@Component({
  selector: 'chips-autocomplete-example',
  templateUrl: 'chips-autocomplete-example.html',
  styleUrls: ['chips-autocomplete-example.css']
})
export class ChipsAutocompleteExample {
  visible: boolean = true;
  selectable: boolean = true;
  removable: boolean = true;
  addOnBlur: boolean = false;

  separatorKeysCodes = [ENTER, COMMA];

  fruitCtrl = new FormControl();

  filteredFruits: Observable<any[]>;

  fruits = [
    'Lemon',
  ];

  allFruits = [
    'Apple',
    'Lemon',
    'Lime',
    'Orange',
    'Strawberry'
  ];

  @ViewChild('fruitInput') fruitInput: ElementRef;

  constructor() {
    this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
        startWith(null),
        map((fruit: string | null) => fruit ? this.filter(fruit) : this.allFruits.slice()));
  }

  add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;

    // Add our fruit
    if ((value || '').trim()) {
      this.fruits.push(value.trim());
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }

    this.fruitCtrl.setValue(null);
  }

  remove(fruit: any): void {
    const index = this.fruits.indexOf(fruit);

    if (index >= 0) {
      this.fruits.splice(index, 1);
    }
  }

  filter(name: string) {
    return this.allFruits.filter(fruit =>
        fruit.toLowerCase().indexOf(name.toLowerCase()) === 0);
  }

  selected(event: MatAutocompleteSelectedEvent): void {
    this.fruits.push(event.option.viewValue);
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  }
}


/**  Copyright 2018 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */
<mat-form-field class="demo-chip-list">
  <mat-chip-list #chipList>
    <mat-chip
      *ngFor="let fruit of fruits"
      [selectable]="selectable"
      [removable]="removable"
      (removed)="remove(fruit)">
      {{fruit}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input
      placeholder="New fruit..."
      #fruitInput
      [formControl]="fruitCtrl"
      [matAutocomplete]="auto"
      [matChipInputFor]="chipList"
      [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
      [matChipInputAddOnBlur]="addOnBlur"
      (matChipInputTokenEnd)="add($event)"
    />
  </mat-chip-list>
  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
    <mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
      {{ fruit }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

<!-- Copyright 2018 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->
angular angular-material
5个回答
8
投票

您可以检查该项目是否已存在于数组中,然后添加。

尝试这样:

// Add our fruit
if ((value || '').trim()) {
  if(!this.fruits.includes(value.trim())) {
    this.fruits.push(value.trim());
  }
}

// Add our fruit
if ((value || '').trim()) {
    let index =   this.fruits.indexOf(value.trim())
    if(index == -1)
      this.fruits.push(value.trim());
}

1
投票

要从列表中删除它,当元素已添加时,请将其从选项中删除,如下所示:

<mat-option *ngIf="!fruits.includes(fruit)" [value]="fruit">
  {{fruit}}
</mat-option>

0
投票

您可以检查所选事件是否已添加芯片。替换这个:

  selected(event: MatAutocompleteSelectedEvent): void {
    this.fruits.push(event.option.viewValue);
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  }

这样:

  selected(event: MatAutocompleteSelectedEvent): void {
    if (!this.fruits.includes(event.option.viewValue)) {
      this.fruits.push(event.option.viewValue);
    }
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  }

0
投票

我是角度初学者,也面临类似的问题。这就是我在选择触发所选功能的复选框时解决该问题的方法,因此您必须解决那里的问题。

 selected(event: MatAutocompleteSelectedEvent): void {
    if (!this.fruits.includes(event.option.viewValue)) {
      this.fruits.push(event.option.viewValue);
    }

    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  }

0
投票

问题在于 Autocomplete 绑定到 Observable,以便可以实时检测击键变化。

假设您正在制作 Mat Chips 演示。

所以对我来说,我最终修改了 Selected 事件并从“allFruits 数组中拼接了所选类别

    const index = this.allFruits.indexOf(event.option.viewValue);    
    if (index >= 0) {
      this.allFruits.splice(index, 1);
    }

这删除了底层数组,但没有删除filteredFruits$。我需要触发过滤机制,以便过滤器能够在更新后的 allFruits 数组上再次工作。

我知道 FormControl 方法有 UpdateValueAndValidity ,但这不起作用,直到我找到了两个可以使用它的参数。

  • onlySelf:更新控制为真。
  • emitEvent:触发valueChanges。

所以我添加了并且它起作用了......

this.fruitCtrl.updateValueAndValidity({ onlySelf: false, emitEvent: true });
© www.soinside.com 2019 - 2024. All rights reserved.