-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
chips-autocomplete-example.ts
66 lines (54 loc) · 1.88 KB
/
chips-autocomplete-example.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent} from '@angular/material/legacy-autocomplete';
import {MatLegacyChipInputEvent} from '@angular/material/legacy-chips';
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 {
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>;
constructor() {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => (fruit ? this._filter(fruit) : this.allFruits.slice())),
);
}
add(event: MatLegacyChipInputEvent): void {
const value = (event.value || '').trim();
// Add our fruit
if (value) {
this.fruits.push(value);
}
// Clear the input value
event.chipInput!.clear();
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().includes(filterValue));
}
}