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

1

2

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>
Pneumoconiosis answered 23/1, 2020 at 19:24 Comment(0)
C
6

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

Capstan answered 23/1, 2020 at 21:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.