angular field in custom form control getting delayed updates

Discussão em 'Angular' iniciado por Dave Vronay, Março 3, 2025.

  1. Dave Vronay

    Dave Vronay Guest

    I have a custom input field in Angular. My custom control has an @Input() that is bound to the value of the input field. When I try to use it in a form, I can see that writeValue is being called, but the new value does not display until I call writeValue again. The normal input field does not do this. Any idea what I am doing wrong?

    my control's HTML (vdsfield.component.html):

    <input (input)="handleFieldChange($event)"
    [type]="inputType" [disabled]="disabled"
    [placeholder]="placeholder"
    [value]="value"/>
    <span *ngIf="error" class="error-icon"><span>!</span></span>


    The typescript:

    import {Component, forwardRef, Input} from '@angular/core';
    import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';

    @Component({
    // tslint:disable-next-line:component-selector
    selector: 'vds-field',
    templateUrl: './vdsfield.component.html',
    styleUrls: ['./vdsfield.component.scss'],
    providers: [
    {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => VDSFieldComponent),
    multi: true
    }
    ]
    })
    export class VDSFieldComponent implements ControlValueAccessor {

    @Input() placeholder: string;
    @Input() value: string;
    @Input() disabled: boolean;
    @Input() inputType = 'text';
    @Input() error = false;

    constructor() { }

    propagateChange = (_: any) => {};

    handleFieldChange(e) {
    this.value = e.target.value;
    console.log('field changed');
    this.propagateChange(this.value);
    }

    writeValue(obj: any): void {
    if (obj !== undefined) {
    this.value = obj;
    console.log('Writing value:' + obj);
    }
    }

    registerOnChange(fn) {
    this.propagateChange = fn;
    }

    registerOnTouched(fn) {
    }
    }


    When I change the model, I can see that writeValue is being called with the new value via the console.log, but the inner control does not update. When I set the value again, the previous value is drawn. If I use a normal field in the form instead of my custom control, it does not do this.

    Thanks in advance!

    Continue reading...

Compartilhe esta Página