如何停止在角垫芯片中添加新值以及重复值?

时间:2020-08-10 17:26:35

标签: angular angular-material angular9

我正在使用角度9块筹码,我想知道如何停止在输入中添加新值,而只允许添加自动完成列表中的项目,即键入不在列表中的“ abc”自动完成列表,然后按Enter键,在输入中添加“ abc作为筹码”,需要避免的是,仅应添加自动完成列表中的值。另外,我想知道如何停止在有角度的垫片中添加重复项,即,如果我已经添加了柠檬,就不应该将柠檬添加到垫片列表中,也应该从自动完成列表中删除。

以下是代码:

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

chip-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>

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

6 个答案:

答案 0 :(得分:0)

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

尝试这样:

//更新add(事件:MatChipInputEvent)

SELECT COUNT(id_pad) over(), id_pad AS COUNT_PADS FROM tbl_pads group by id_pad;

答案 1 :(得分:0)

为避免重复,请将您选择的功能更改为以下

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

答案 2 :(得分:0)

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

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

以及所有构造器的filter方法。

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.

答案 3 :(得分:0)

如Lakshmi Narayan在他的答案中所述,修改选定的功能可停止添加重复项。除此之外,添加功能中的附加检查会停止在自动完成列表之外添加值,如下所示:

选择功能

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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

除了要防止将重复项添加到列表中,您还可以将其隐藏在下拉列表中,如下所示:

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