All files / app/component/list-editor list-editor.component.ts

48.64% Statements 18/37
55.55% Branches 10/18
33.33% Functions 2/6
40% Lines 12/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 6569x                 69x 2x     2x   2x   2x   2x   2x   2x   2x 2x   2x                                                                        
import { Component, EventEmitter, HostBinding, Input, Output } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
 
@Component({
  selector: 'app-list-editor',
  templateUrl: './list-editor.component.html',
  styleUrls: ['./list-editor.component.scss'],
  imports: [ReactiveFormsModule]
})
export class ListEditorComponent{
  @HostBinding('class') css = 'listbox form-group';
 
  @Input()
  list: string[] = [];
  @Input()
  type = 'email';
  @Input()
  placeholder = 'Add item';
  @Output()
  onAdd = new EventEmitter<string>();
  @Output()
  onRemove = new EventEmitter<string>();
  @Output()
  selected = new EventEmitter<string>();
 
  addingText = '';
  selectedIndex = -1;
 
  error = '';
 
  add() {
    this.error = '';
    if (!this.addingText) return;
    if (this.list.includes(this.addingText)) {
      this.error = 'Duplicate name';
      return;
    }
    this.list.push(this.addingText);
    this.onAdd.emit(this.addingText);
    this.addingText = '';
    this.select(this.list.length - 1);
  }
 
  remove(index: number) {
    this.onRemove.emit(this.list[index]);
    this.list.splice(index, 1);
  }
 
  select(index: number) {
    this.selectedIndex = index;
    if (index !== -1) {
      this.selected.emit(this.list[index]);
    } else {
      this.selected.emit(undefined);
    }
  }
 
  keydown(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.add();
      event.preventDefault();
    }
  }
}