Advertisement
Guest User

Untitled

a guest
Nov 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import { Component, Input, forwardRef } from '@angular/core';
  2. import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, Validator } from '@angular/forms';
  3.  
  4. const noop = () => {
  5. console.log("NOOP")
  6. };
  7.  
  8. @Component({
  9. selector: 'json-input',
  10. template:
  11. `
  12. <div class="form-group">
  13. <label><ng-content></ng-content>
  14. <input [(ngModel)]="value"
  15. class="form-control"
  16. (blur)="onBlur()" >
  17. </label>
  18. </div>
  19. `,
  20. providers: [
  21. {
  22. provide: NG_VALUE_ACCESSOR,
  23. useExisting: forwardRef(() => TextInputExtComponent),
  24. multi: true,
  25. },
  26. {
  27. provide: NG_VALIDATORS,
  28. useExisting: forwardRef(() => TextInputExtComponent),
  29. multi: true,
  30. }]
  31. })
  32. export class TextInputExtComponent implements ControlValueAccessor {
  33.  
  34. private parseError: boolean;
  35.  
  36. //The internal data model
  37. private innerValue: any = '';
  38.  
  39. //Placeholders for the callbacks which are later providesd
  40. //by the Control Value Accessor
  41. private onTouchedCallback: () => void = noop;
  42. private onChangeCallback: (_: any) => void = noop;
  43.  
  44. //get accessor
  45. get value(): any {
  46. return this.innerValue;
  47. };
  48.  
  49. //set accessor including call the onchange callback
  50. set value(v: any) {
  51. if (v !== this.innerValue) {
  52. this.innerValue = v;
  53. this.onChangeCallback(v);
  54. }
  55. }
  56.  
  57. public validate(c: FormControl) {
  58. return (!this.parseError) ? null : {
  59. jsonParseError: {
  60. valid: false,
  61. },
  62. };
  63. }
  64. //Set touched on blur
  65. onBlur() {
  66. console.log("serdgfWEF")
  67. this.onTouchedCallback();
  68. }
  69.  
  70. //From ControlValueAccessor interface
  71. writeValue(value: any) {
  72. if (value !== this.innerValue) {
  73. this.innerValue = value;
  74. }
  75. }
  76.  
  77. //From ControlValueAccessor interface
  78. registerOnChange(fn: any) {
  79. this.onChangeCallback = fn;
  80. }
  81.  
  82. //From ControlValueAccessor interface
  83. registerOnTouched(fn: any) {
  84. this.onTouchedCallback = fn;
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement