Search code examples
angularangular2-formsangular2-formbuilderangular2-form-validationignite-ui-angular

Angular, is there a way to "markAsTouched" a field without a Form?


I've already know that input items inside a FormControl can be mark dirt or touched by calling any of the following methods (maybe more): group.markAsTouched(); form.get('control-name').markAsTouched(); form.markAllAsTouched(); form.controls[someIndex].markAsTouched();

However, I can see that the markAsTouched method seems to be called when the input is focus and then blur.

Is there a way to achieve the same result by code?? lets say, when clicked a button.


Here, you can see a gif of the current standard behaviour without a form, also you can test it yourself at the following live sample:

https://stackblitz.com/edit/angular-peq11f

To me, it seems obvious that this behaviour should be available to be triggered by code and not only when blur event is triggered

Something like this:

<input #myInput>
<button (click)="myInput.markAsTouched()">click</button>

Solution

  • You can use an unique formControl <input [formControl]="control"> and markAsTouched

    <input [formControl]="control">
    <button (click)="control.markAsTouched()">click</button>
    {{control.touched}}
    

    Where you has in .ts

    // as a property
    control = new FormControl();
    
    // or in a function
    this.control.markAsTouched();
    

    A FormControl can belong to a FormGroup or not. furthermore, It's not necessary to have a tag input. We are using a tag input to change the value, but if you remove the input, the control is mark as touched too