1

I've been searching for a solution on this but can't find what I'm looking for. I have this form and as soon as any field gets touched I want to console out a message in ngOnInit. So far if I enter a value in any field I can show a message ("You entered a value"), but I want to be able to show a message when user touches the field. Can anyone point me in the right direction? Here's my code.

LIVE DEMO Thanks a lot in advance!

 ngOnInit() {
 this.myForm.valueChanges.subscribe(res => {
  console.log("You entered a value");
  // Here I want to show a message ("A field has been touched") when any field of the form gets touched
 })
}
HenryDev
  • 4,685
  • 5
  • 27
  • 64

2 Answers2

2

Use the (mousedown) event in Angular

Here is a quick demo StackBlitz

John Velasquez
  • 3,421
  • 2
  • 18
  • 23
  • I tried that before, but the problem with that is that I will have to add the mousedown event to every single field in the form and my form has 20+ fields so the view will have a bunch of mousedown events all over and it doesn't seem to be a good practice. I'm trying to accomplish this ONLY from the component – HenryDev Feb 01 '19 at 14:01
2

There isn't anything available out of the box for forms, AFAIK.

I guess you could leverage HostListener that is triggered for example in what dom event you want, for example focusin. You can have that in the component, or create a separate directive.

Sample:

@HostListener('focusin', ['$event']) onFocus(event) {
  console.log('a field was focused!')
}

Hopefully this is a suitable work-around (I guess it would be classified as one?)

AT82
  • 71,416
  • 24
  • 140
  • 167