6

Is there a simple way to prevent an input control from dirtying its parent form? I could do so by building a custom tag that doesn't have a controlValueAccessor, but I was wondering if there is an easier way.

In the middle of one of my forms I have an input that takes a number next to a button. The input is just to specify how many of a certain type of item I want to add to a set of things. The input where you specify how many is not relevant to whether the form should be considered dirty as there are no "changes" to the form until the add button is clicked at which point a bunch of items get added to the set and I propagate changes from there.

Devon Holcombe
  • 518
  • 1
  • 5
  • 18

1 Answers1

4

If you are using template-driven forms, you can use

[ngModelOptions]="{standalone: true}"

This is specifically defined for your scenario. From the documentation:

standalone: Defaults to false. If this is set to true, the ngModel will not register itself with its parent form, and will act as if it's not in the form. This can be handy if you have form meta-controls, a.k.a. form elements nested in the tag that control the display of the form, but don't contain form data.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • 2
    Do you know how to do this for a reactive form? – Domenick Jul 24 '18 at 19:24
  • You don't need to do this for reactive forms. Just don't put it into your form structures in your code and don't assign the element a formControlName. Or am I missing the point of your question? – DeborahK Jul 24 '18 at 19:31
  • I want to know when the inputs are touched but I do not want them to dirty the form. Right now I have a workaround `(input)="markPristine()"` and the function marks the inputs to pristine. I didn't know if there was an easier way. – Domenick Jul 24 '18 at 20:13
  • 1
    Don't know if it is easier, but you could leave it out of your form structure, remove the formControlName, then watch for `touched` manually. The question is whether you want the value to remain in the formProperty.value. – DeborahK Jul 24 '18 at 20:16
  • 1
    @Domenick this could cause problems if you had already changed another form field that changes should alert a pristine status. – Leonardo Rick Mar 03 '21 at 21:00