How do I get reference to the FormControl from a component that implements...

Discussão em 'Angular' iniciado por tt9, Novembro 11, 2024.

  1. tt9

    tt9 Guest

    I created an Angular component derived from this blog post. I have it in a reactive form and I would like to get the errors on the form control, the component itself will have a stylized error message that it will render when the control has an error on it. However when I try to inject the NgControl class into the component I am getting circular reference issues, so how would I access the errors on the control?

    Here is the current code, it's not complete yet but it should give the basic idea of what I am trying to accomplish:

    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>
    <!-- I will have an NGIF here to check for errors before rendering the error -->
    <div class="form-error">
    {{ error }}
    </div>
    </div>

    Continue reading...

Compartilhe esta Página