bstlboard-front/src/app/ui/tags/tagspicker.ui.ts

89 lines
2.3 KiB
TypeScript

import { COMMA, ENTER, SPACE } from '@angular/cdk/keycodes';
import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MatChipInputEvent } from '@angular/material/chips';
import { Observable } from 'rxjs';
import { debounceTime, switchMap } from 'rxjs/operators';
import { TagsService } from 'src/app/services/tags.service';
@Component({
selector: 'ui-tagspicker',
templateUrl: './tagspicker.ui.html',
styleUrls: ['./tagspicker.ui.scss']
})
export class UiTagsPicker implements OnInit {
@Input() change: Function;
@Input() model: any;
@Input() placeholder: string;
@Input() appearance: string;
@Input() max: number = 0;
tags: string[] = [];
searchTags: Observable<Object>;
@ViewChild('tagsInput') tagsInput: ElementRef<HTMLInputElement>;
searchFormControl = new FormControl();
readonly separatorKeysCodes = [ENTER, COMMA, SPACE] as const;
constructor(private tagsService: TagsService) { }
ngOnInit(): void {
this.searchTags = this.searchFormControl
.valueChanges
.pipe(
debounceTime(300),
switchMap(value => {
if (value.startsWith('#')) {
value = value.replace('#', '');
}
value = value.split('#').join('-');
return this.tagsService.search(value);
})
);
this.tags = this.model || [];
}
addTag(tag: string) {
if (tag.startsWith('#')) {
tag = tag.replace('#', '');
}
tag = tag.split('#').join('-');
if (tag && this.tags.indexOf(tag) == -1 && (this.max == 0 || this.tags.length < this.max)) {
this.tags.push(tag);
}
this.model = this.tags;
if (this.change) {
this.change(this.model);
}
this.tagsInput.nativeElement.value = '';
}
addInputTag(event: MatChipInputEvent): void {
this.addTag((event.value || "").trim())
event.chipInput!.clear();
}
addOptionTag(event: MatAutocompleteSelectedEvent): void {
this.addTag((event.option && event.option.value || "").trim());
}
removeTag(tag: string): void {
const index = this.tags.indexOf(tag);
if (index >= 0) {
this.tags.splice(index, 1);
}
this.model = this.tags;
if (this.change) {
this.change(this.model);
}
}
}