Building  Large-Scale Web Applications with Angular
上QQ阅读APP看书,第一时间看更新

More on NgForm

Forms in Angular have a different role to play as compared to traditional forms that post data to the server. If we go back and look again at the form tag, we will see that it is missing the standard action attribute. The standard form behavior of posting data to the server using full-page post-back does not make sense with an SPA framework such as Angular. In Angular, all server requests are made through asynchronous invocations originating from directives or services.

Under the hood, Angular is also turning off the browser's inbuilt validation. As you have seen in this chapter, we are still using validation attributes such as required that look the same as native HTML validation attributes. However, as the Angular documentation explains, inside an Angular form "Angular uses directives to match these attributes with validator functions in the framework." See  https://angular.io/guide/form-validation#template-driven-validation.

The form here plays a different role. When the form encapsulates a set of input elements (such as input, textarea, and select) it provides an API for:

  • Determining the state of the form, such as whether the form is dirty or pristine based on the input controls on it
  • Checking validation errors at the form or control level

If you still want the standard form behavior, you can add an ngNoForm attribute to the form element, but this will definitely cause a full-page refresh. You can also turn on the browser's inbuilt validation by adding the ngNativeValidate attribute. We'll explore the specifics of the NgForm API a little later in this chapter when we look at saving the form and implementing validation. 

The state of the FormControl objects within the form is being monitored by NgForm. If any of them are invalid, then NgForm sets the entire form to invalid. In this case, we have been able to use NgForm to determine that one or more of the FormControl objects is invalid and therefore the state of the form as a whole is invalid too.

Let's look at one more issue before we finish this chapter.