Template-Drive angular form
ngSubmit is used as listener to handle submit
- In order to check form object automatically generated by Angular, you can use the following method:
- <form (ngSubmit) = “onSubmit(f) #f = “ngForm”> … </form>
Assign “ngModel” for every form control to let Angular know this element is form control: <input type=”text” name=”name” ngModel>
Also can set default value to the form control using ngModel data binding, such as: <input type=”text” name=”name” [ngModel] = “‘John CJ'”>
- You can group a set of form control as a group to test validation using ngModelGroup directive, also set local reference as ngModelGroup to access this Object to control the tag, such as:
- <div ngModelGroup = “userData” #dataGroup = “ngModelGroup”> … </div>
- then, in browser console, in ngForm Object, in controls property, there should be one property called “userData” that control the group of these form controls you set up. And in HTML template, you can use local reference “dataGroup” to access this group of form control
- Two methods can be used to set form controls value:
- localreference-name.setValue( { must include every form control, and the data structure should also be the same as form data structure} ); // note: using this method, the all of form controls will be replaced, even you input some data already.
- localreference-name.form.patchValue({ must use form data structure locating the data you want to set }); //note: this method only change the data you want, if you already input some data, this method will
Check out the Validators class: https://angular.io/api/forms/Validators
For the template-driven approach, you need the directives. You can find out their names, by searching for “validator” in the official docs: https://angular.io/api?type=directive – everything marked with “D” is a directive and can be added to your template.