如何停止在 angular mat-chips 中添加新值和重复值?

How can I stop adding new values as well as duplicate values in angular mat-chips?

我正在使用 angular 9 mat-chips,我想知道如何停止在输入中添加新值并只允许添加自动完成列表中的项目,即输入 'abc' 不在自动完成列表中,按回车键会在需要避免的输入中添加 'abc as a chip',只应添加自动完成列表中的值。另外,我想知道如何停止在 angular mat-chips 中添加重复项,即如果我已经添加了 lemon lemon,则不应将其添加到 mat-chips 列表中,也应从自动完成列表中删除。

代码如下:

芯片-autocomplete.component.ts

@Component({
  selector: 'chips-autocomplete-example',
  templateUrl: 'chips-autocomplete-example.html',
  styleUrls: ['chips-autocomplete-example.css'],
})

export class ChipsAutocompleteExample {
  visible = true;
  selectable = true;
  removable = true;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  fruitCtrl = new FormControl();
  filteredFruits: Observable<string[]>;
  fruits: string[] = ['Lemon'];
  allFruits: string[] = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];

  @ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
  @ViewChild('auto') matAutocomplete: MatAutocomplete;

  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: string): void {
    const index = this.fruits.indexOf(fruit);

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

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

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
  }
}

芯片-autocomplete.component.html

<mat-form-field class="example-chip-list">
  <mat-chip-list #chipList aria-label="Fruit selection">
    <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"
      (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>

app.component.html

<div class="mat-app-background basic-container">
  <chips-autocomplete-example>loading</chips-autocomplete-example>
</div>

可以在以下位置找到类似于此代码的 stackblitz(来自 angular material 设计):https://stackblitz.com/angular/gdjdrkxaedv?file=src%2Fapp%2Fchips-autocomplete-example.ts

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

这样试试:

//更新添加(事件:MatChipInputEvent)

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

为避免重复将您选择的函数更改为以下

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

您可以添加过滤方法来删除下拉列表中的重复条目。

getUniqueList(fruitList: string[]) {
  return fruitList.filter(x => this.fruits.indexOf(x) === -1);
}

以及构造函数的所有过滤器方法。

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

然后添加对删除方法的更新

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

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

要添加独特的项目,您可以使用以下代码。

// Add our fruit
if ((value || "").trim()) {
  const filterList = this.getUniqueList(this.allFruits);
  const index = filterList.indexOf(event.value);
  if (index > -1) {
    this.fruits.push(value.trim());
  }
}

您可以参考更新后的代码here.

正如 Lakshmi Narayan 在他的回答中所说,修改 selected 函数会停止添加重复项。除此之外,添加功能的附加检查停止在自动完成列表之外添加值,如下所示:

select函数

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

修改添加函数

add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;
    if(this.allFruits.indexOf(value) !== -1){
      // Add our fruit
      if ((value || '').trim()) {
        this.fruits.push(value.trim());
      }
    }

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

    this.fruitCtrl.setValue(null);
  }

我不确定我是否理解正确? 但是我创建了一个最小的工作示例。

https://stackblitz.com/edit/angular-eooxih?file=src%2Fapp%2Fchips-autocomplete-example.html

模板

  <mat-form-field color="primary" style="width: 100%">
    <mat-label> Label</mat-label>
    <mat-select [formControl]="fruitCtrl" #multiSelect multiple>
      <mat-select-trigger>
        <mat-chip-list #chipList selected>
          <ng-container>
            <mat-chip color="primary" *ngFor="let fruit of fruitCtrl?.value; let matChipIndex = index" class="font-weight-normal" selected
              [removable]="true" (removed)="onRemoveFruit(multiSelect, matChipIndex)">
              {{fruit}}
              <mat-icon matChipRemove>cancel</mat-icon>
            </mat-chip>
          </ng-container>
        </mat-chip-list>
      </mat-select-trigger>
      <mat-option *ngFor="let item of allFruits" [value]="item">
        {{item}}
      </mat-option>
    </mat-select>
  </mat-form-field>

TS 进口

import { Component } from "@angular/core";
import { FormControl } from "@angular/forms";
import { MatSelect, MatSelectChange } from "@angular/material/select";

TS

export class Component {
  fruitCtrl = new FormControl([]);
  allFruits: string[] = ["Apple", "Lemon", "Lime", "Orange", "Strawberry"];

  constructor() {}

  onRemoveFruit(multiSelect: MatSelect, matChipIndex: number) {
    const selectedFruits = [...this.fruitCtrl.value];
    selectedFruits.splice(matChipIndex, 1);
    this.fruitCtrl.patchValue(selectedFruits);

    multiSelect.writeValue(selectedFruits);
  }
}

除了防止重复项被添加到列表中,您还可以像这样将它们隐藏在下拉列表中:

      <ng-container *ngFor="let fruit of filteredFruits | async">
        <mat-option *ngIf="!fruits.includes(fruit)" [value]="fruit">
          {{fruit}}
        </mat-option>
      </ng-container>