clr-checkbox-group.component.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { Component, Attribute, OnInit } from '@angular/core';
  2. import { FormControl } from '@angular/forms';
  3. import { GroupInputComponent } from '../../_abstract/group-input.component';
  4. @Component({
  5. selector: 'app-checkbox-group',
  6. templateUrl: './clr-checkbox-group.component.html',
  7. styleUrls: ['./clr-checkbox-group.component.scss']
  8. })
  9. export class ClrCheckboxGroupComponent extends GroupInputComponent implements OnInit {
  10. firstControl: FormControl;
  11. constructor(
  12. @Attribute('firstEnablesRest') private firstEnablesRest,
  13. @Attribute('allOrNone') private showAllOrNone
  14. ) {
  15. super();
  16. this.firstEnablesRest = firstEnablesRest === ''; // True if 'firstEnablesRest' exists as component attribute
  17. this.showAllOrNone = showAllOrNone === ''; // True if 'firstEnablesRest' exists as component attribute
  18. }
  19. ngOnInit() {
  20. super.ngOnInit();
  21. if (this.meta.firstEnablesRest) {
  22. this.firstEnablesRest = this.meta.firstEnablesRest;
  23. }
  24. if (this.meta.showAllOrNone) {
  25. this.showAllOrNone = this.meta.showAllOrNone;
  26. }
  27. if (this.firstEnablesRest) {
  28. this.firstControl = this.formGroup.controls[this.controlNames[0]] as FormControl;
  29. this.childMetaArray[0].disabled = false;
  30. this.childMetaArray.slice(1).map(meta => { meta.disabled = !this.firstControl.value; return meta; });
  31. // Observe value changes on first control
  32. this.firstControl.valueChanges.subscribe(val => {
  33. for (let i = 1; i < this.childMetaArray.length; i++) {
  34. // NOTE: We reassign the input (array member) to trigger change detection (otherwise it doesn't run)
  35. // See https://juristr.com/blog/2016/04/angular2-change-detection/
  36. this.childMetaArray[i] = {
  37. ...this.childMetaArray[i],
  38. disabled: !val
  39. };
  40. }
  41. });
  42. }
  43. }
  44. selectAll(e: Event): false {
  45. this.controlNames.forEach(c => this.formGroup.get(c).setValue(this.meta.meta[c].value));
  46. (e.target as HTMLLinkElement).blur();
  47. return false;
  48. }
  49. selectNone(e: Event): false {
  50. this.controlNames.forEach(c => this.formGroup.get(c).setValue(null));
  51. (e.target as HTMLLinkElement).blur();
  52. return false;
  53. }
  54. }