Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Custom Form Component: Provide a markTouched method

I have a custom form component that implements ControlValueAccessor. This component has an internal property touched.

export class BmInputComponent implements ControlValueAccessor, Validator {

    private onTouchedCallback: () => {};
    private touched: boolean = false;

    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }

    onBlur() {
        this.touched = true;
        this.onTouchedCallback();
    }
}

I need to implement a method like

markTouched() {
    this.touched = true;
}

That could be called by the user of the component when markAsTouched is executed in the formControl: customInputControl.markAsTouched()

I cannot find an angular-way to do this.

@Edit: Tried to inject the NgControl:

@Component({
    selector: 'bm-input',
    templateUrl: './bm-input.component.html',
    encapsulation: ViewEncapsulation.None,
    providers: [
         {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => BmInputComponent),
            multi: true
        }
    ]
})
export class BmInputComponent implements ControlValueAccessor, Validator {

    private onTouchedCallback: () => {};
    private touched: boolean = false;

    constructor(@Self() @Optional() public _formControl: NgControl) {
        this._viewDate = new Date();
        if (this._formControl) {
            this._formControl.valueAccessor = this;
            this._formControl.statusChanges.subscribe(this.markTouched);
        }
    }
    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }

    onBlur() {
        this.touched = true;
        this.onTouchedCallback();
    }

    markTouched() {
        if(this._formControl.touched)
            this.touched = true;
    }

}

But I am getting Cannot instantiate cyclic dependency! NgControl when the component is invoked with a formControl.

like image 395
Zucca Avatar asked Jul 30 '26 04:07

Zucca


1 Answers

Have you tried @SkipSelf() instead of @Self()?

like image 123
user1678153 Avatar answered Aug 01 '26 18:08

user1678153



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!