I created an Angular component derived from this blog post . I have this in a reactive form, and I would like to get errors in the form control, the component itself will have a stylized error message that will be displayed when the control has an error. However, when I try to introduce the NgControl class into the component, I get circular reference problems, so how can I access the errors in the control?
Here is the current code, it is not complete yet, but it should give a basic idea of ββwhat I'm trying to execute:
import { Component, Output, EventEmitter, Input, forwardRef } from '@angular/core';
import {
NgControl,
NG_VALUE_ACCESSOR,
ControlValueAccessor,
Validator,
AbstractControl,
FormControl,
NG_VALIDATORS
} from '@angular/forms';
@Component({
selector: 'form-field-input',
templateUrl: './form-field-input.component.html',
styleUrls: ['./form-field-input.component.less'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => FormFieldInputComponent),
multi: true
}]
})
export class FormFieldInputComponent implements ControlValueAccessor {
private propagateChange = (_: any) => { };
private propagateTouch = (_: any) => { };
@Input('label') label: string;
@Input('type') type: string;
@Input('id') id: string;
@Input('formControlName') formControlName: string;
@Input('error') error: string;
@Input('classes') classes: any;
private value: string;
private data: any;
constructor() {
debugger;
}
private onChange(event) {
this.data = event.target.value;
this.propagateChange(this.data);
this.propagateTouch(this.data);
}
writeValue(obj: any): void {
this.data = obj;
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
this.propagateTouch = fn;
}
}
template file:
<div class="form-field-input-component">
<input id="{{id}}"
type="{{type}}"
class="form-field-input"
[value]="data"
(change)="onChange($event)"
(keyup)="onChange($event)" />
<span class="context-icon fa fa-lock"></span>
<span class="info-icon fa fa-info-circle"></span>
<div class="form-error">
{{ error }}
</div>
</div>
source
share