Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, Input, forwardRef } from '@angular/core';
- import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, Validator } from '@angular/forms';
- const noop = () => {
- console.log("NOOP")
- };
- @Component({
- selector: 'json-input',
- template:
- `
- <div class="form-group">
- <label><ng-content></ng-content>
- <input [(ngModel)]="value"
- class="form-control"
- (blur)="onBlur()" >
- </label>
- </div>
- `,
- providers: [
- {
- provide: NG_VALUE_ACCESSOR,
- useExisting: forwardRef(() => TextInputExtComponent),
- multi: true,
- },
- {
- provide: NG_VALIDATORS,
- useExisting: forwardRef(() => TextInputExtComponent),
- multi: true,
- }]
- })
- export class TextInputExtComponent implements ControlValueAccessor {
- private parseError: boolean;
- //The internal data model
- private innerValue: any = '';
- //Placeholders for the callbacks which are later providesd
- //by the Control Value Accessor
- private onTouchedCallback: () => void = noop;
- private onChangeCallback: (_: any) => void = noop;
- //get accessor
- get value(): any {
- return this.innerValue;
- };
- //set accessor including call the onchange callback
- set value(v: any) {
- if (v !== this.innerValue) {
- this.innerValue = v;
- this.onChangeCallback(v);
- }
- }
- public validate(c: FormControl) {
- return (!this.parseError) ? null : {
- jsonParseError: {
- valid: false,
- },
- };
- }
- //Set touched on blur
- onBlur() {
- console.log("serdgfWEF")
- this.onTouchedCallback();
- }
- //From ControlValueAccessor interface
- writeValue(value: any) {
- if (value !== this.innerValue) {
- this.innerValue = value;
- }
- }
- //From ControlValueAccessor interface
- registerOnChange(fn: any) {
- this.onChangeCallback = fn;
- }
- //From ControlValueAccessor interface
- registerOnTouched(fn: any) {
- this.onTouchedCallback = fn;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement