query-param-name.directive.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import {
  2. Directive,
  3. Inject,
  4. Input,
  5. OnChanges,
  6. OnDestroy,
  7. Optional,
  8. Self,
  9. SimpleChanges
  10. } from '@angular/core';
  11. import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
  12. import { QueryParamGroupService } from './query-param-group.service';
  13. import { QueryParamAccessor } from './query-param-accessor.interface';
  14. import { selectValueAccessor } from '../accessors/util';
  15. /**
  16. * Binds a {@link QueryParam} to a DOM element.
  17. *
  18. * This directive accepts the name of a {@link QueryParam} inside its parent {@link QueryParamGroup}.
  19. * It binds this parameter to the host element, which is required to have a [ControlValueAccessor]
  20. * {@link https://angular.io/api/forms/ControlValueAccessor}.
  21. */
  22. @Directive({
  23. selector: '[queryParamName]'
  24. })
  25. export class QueryParamNameDirective implements QueryParamAccessor, OnChanges, OnDestroy {
  26. /**
  27. * The name of the {@link QueryParam} inside its parent {@link QueryParamGroup}.
  28. * Note that this does not refer to the [parameter name]{@link QueryParam#urlParam}.
  29. */
  30. @Input('queryParamName')
  31. public name: string;
  32. /** @internal */
  33. public valueAccessor: ControlValueAccessor | null = null;
  34. constructor(
  35. @Optional() private groupService: QueryParamGroupService,
  36. @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]
  37. ) {
  38. if (!this.groupService) {
  39. throw new Error(
  40. `No parent configuration found. Did you forget to add [queryParamGroup]?`
  41. );
  42. }
  43. this.valueAccessor = selectValueAccessor(valueAccessors);
  44. }
  45. /** @ignore */
  46. public ngOnChanges(changes: SimpleChanges) {
  47. const nameChange = changes['name'];
  48. if (nameChange) {
  49. if (!nameChange.firstChange) {
  50. this.groupService.deregisterQueryParamDirective(nameChange.previousValue);
  51. }
  52. if (nameChange.currentValue) {
  53. this.groupService.registerQueryParamDirective(this);
  54. }
  55. }
  56. }
  57. /** @ignore */
  58. public ngOnDestroy() {
  59. if (this.groupService) {
  60. this.groupService.deregisterQueryParamDirective(this.name);
  61. }
  62. }
  63. }