aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/shared-forms/select/select-categories.component.ts
blob: b921714ff4ac526df02a1b5c6b83204317d31a41 (plain) (blame)
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
67
68
69
70
71
import { Component, forwardRef, OnInit } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
import { ServerService } from '@app/core'
import { SelectOptionsItem } from '../../../../types/select-options-item.model'
import { ItemSelectCheckboxValue } from './select-checkbox.component'

@Component({
  selector: 'my-select-categories',
  styleUrls: [ './select-shared.component.scss' ],
  templateUrl: './select-categories.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SelectCategoriesComponent),
      multi: true
    }
  ]
})
export class SelectCategoriesComponent implements ControlValueAccessor, OnInit {
  selectedCategories: ItemSelectCheckboxValue[] = []
  availableCategories: SelectOptionsItem[] = []

  allCategoriesGroup = $localize`All categories`

  // Fix a bug on ng-select when we update items after we selected items
  private toWrite: any
  private loaded = false

  constructor (
    private server: ServerService
  ) {

  }

  ngOnInit () {
    this.server.getVideoCategories()
      .subscribe(
        categories => {
          this.availableCategories = categories.map(c => ({ label: c.label, id: c.id + '', group: this.allCategoriesGroup }))
          this.loaded = true
          this.writeValue(this.toWrite)
        }
      )
  }

  propagateChange = (_: any) => { /* empty */ }

  writeValue (categories: string[] | number[]) {
    if (!this.loaded) {
      this.toWrite = categories
      return
    }

    this.selectedCategories = categories
      ? categories.map(c => c + '')
      : categories as string[]
  }

  registerOnChange (fn: (_: any) => void) {
    this.propagateChange = fn
  }

  registerOnTouched () {
    // Unused
  }

  onModelChange () {
    this.propagateChange(this.selectedCategories)
  }
}