Reactive Forms - mark fields as touched

后端 未结 19 1576
旧时难觅i
旧时难觅i 2020-12-04 23:15

I am having trouble finding out how to mark all form\'s fields as touched. The main problem is that if I do not touch fields and try to submit form - validation error in not

19条回答
  •  执念已碎
    2020-12-04 23:44

    I had this issue but found the "correct" way of doing so, despite it not being in any Angular tutorial I've ever found.

    In your HTML, on the form tag, add the same Template Reference Variable #myVariable='ngForm' ('hashtag' variable) that the Template-Driven Forms examples use, in addition to what the Reactive Forms examples use:

    Now you have access to myForm.submitted in the template which you can use instead of (or in addition to) myFormGroup.controls.X.touched:

    invalid date format date cannot be in the past.

    Know that myForm.form === myFormGroup is true... as long as you don't forget the ="ngForm" part. If you use #myForm alone, it won't work because the var will be set to the HtmlElement instead of the Directive driving that element.

    Know that myFormGroup is visible in your Component's typescript code per the Reactive Forms tutorials, but myForm isn't, unless you pass it in through a method call, like submit(myForm) to submit(myForm: NgForm): void {...}. (Notice NgForm is in title caps in the typescript but camel case in HTML.)

提交回复
热议问题