Angular: Call markAsDirty () on a custom input component from NgForm

I implemented a custom component that is a wrapper for input using NgModel. I linked them to ControlValueAccessor. It works well, I can easily access the values ​​from my parent component.

But if I try to call markAsDirty (), the indirect flag only changes my component, it does not affect my input inside the component. I will give you an example:

// Parent Component onSubmit(form: NgForm) { this.form.controls.registerEmail.markAsDirty(); } // Thats how the component looks like in my form: <form #form="ngForm" (ngSubmit)="onSubmit(form)" [ngClass]="{'has-error': !form.valid}"> <form-text label="E-Mail" name="registerEmail" email required placeholder="" [(ngModel)]="eMail"></form-text> </form> // Result <form-text label="E-Mail" name="registerEmail" class="ng-untouched ng-invalid ng-dirty"> <label for="form-text-2">E-Mail</label> <input class="input-control invalid ng-untouched ng-pristine ng-invalid" type="text" id="form-text-2"> </form-text> 

As you can see, in the form text there is a class "ng-dirty", the input inside remains untouched.

To implement my custom component, I used one of the many instructions that you will find on the Internet. Here is the one I used: angular2 user form control with json input confirmation

I want to mark each input field dirty when I click the submit button. Because my check appears when you blur the input.

I realized that there is a problem that my component inherits from ControlValueAccessor. The only connection between my component and my NgForm is over its NgModel. NgForm can use my component as FormControl because it has its own NgModel. By events, you can transmit values ​​in two directions. But this is not possible with methods like markAsDirty () or markAsTouched (). Inside the component, this is not a problem. But my NgForm has no real component access. Only for NgModel.

Is there any way to implement this? I thought it was not difficult to understand, but I have been struggling with this for a long time. My only solution for now is to iterate over each input using jQuery to trigger focus. There must be a cleaner solution for this.

thanks

+7
javascript validation angular forms
source share
1 answer

You need to call onTouched () (this._onTouchedCallback) from inside your component if you want the control state status to be affected. The same for this ._onChangeCallback

For example, adding (ngModelChange) = "onTouched (value)" to the input tag in my user input

Copied from: https://github.com/angular/angular/issues/10151

0
source share

All Articles