Back to course

TDF: Accessing Form State and Submission

The Complete Angular Developer: From Zero to Hero

44. TDF: Accessing Form State and Submission

The NgForm directive, automatically instantiated on the <form> tag, aggregates the states of all controls within it.

Accessing the Global Form State

By assigning a reference variable to the form itself (e.g., #f="ngForm"), we can access the global form state, which is an aggregate of all controls' states.

html

...
Form Value: {{ f.value | json }}

Form is valid: {{ f.valid }}

The ngSubmit Event

The standard DOM submit event causes a full page reload. Angular prevents this default behavior when you use (ngSubmit) on the <form> element.

Handling Submission

In TDF, the best practice for submission is to pass the entire NgForm object to the component method.

typescript import { NgForm } from '@angular/forms';

export class SubmissionComponent { userModel = { firstName: 'John', lastName: 'Doe' };

onSubmit(form: NgForm) { if (form.valid) { console.log('Data to send:', form.value); // Use form.value

  // After successful submission, you may want to reset the form
  form.resetForm(); 
  // If you want to keep the data model but reset the state:
  // form.resetForm(this.userModel);
}

} }

form.value contains the aggregate key-value object of all inputs that had [(ngModel)] defined. form.resetForm() resets the pristine, touched, and validation states.