Module 10 HTMLForms 2
Module 10 HTMLForms 2
HTML Forms
NOTE: Some information taken from
https://angular.dev/
Follow directions to create a new app
formsApp
Create 3 components:
header
Update the header component html to include some text such as
'HTML Forms' and format in the local header component.css
Startup
template-forms
reactive-forms
Template
NgForm is the directive we need to make the form submittable; this is
Driven added as part of the FormsModule import
Forms
However, the instance of ngForm is hidden so to expose it, we use a
local template reference attached to the form element
<form #f="ngForm">
Now f is the template used to point to the instance of ngForm set for
this particular form
Slide 6
To see if our values are added, we can add an event directive
(ngSubmit) and set to a function
<form #f="ngForm" (ngSubmit)=onSubmit(f)>
Template Click the Submit button and then look in the console; you should see the
Driven instance of ngForm
Forms
When field is selected and then the Submit is clicked, field indicates
something is not correct but does not really tell the user what is wrong
or expected
Slide 8
*ngIf can be used to decide if the control field is 'valid' and also if
'touched' so we can display a more user-friendly message
valid condition met (such as required in this instance)
touched user has at least focused on the field before
showing error
Include the following under the <input> field which needs the
Template
#first="ngModel" shown previously to work (complete #last also)
Driven What is being checked: If field is NOT valid but has been accessed
Forms
<span *ngIf='!first.valid && first.touched'>
This field is required</span>
A default value can be set for the radio button group and select
Template
drop-down by using one-way binding [ngModel] set to a variable
Driven and then variable is set to which value is to be default
Forms
<mat-radio-group> [ngModel]="radioValue"
in .ts file radioValue = 'brampton';
<mat-select> [ngModel]="selectValue"
in .ts file selectValue = 'Davis';
Slide 10
With the reactive form approach, structure is defined in the
TypeScript file (coded), Form set up done in HTML and then
manually connected
To setup submit
<form [formGroup]="sheridanForm" (ngSubmit)="onSubmit()">
https://angular.dev/overview
Sources https://nodejs.org/en/
https://docs.npmjs.com/
https://help.github.com/en
https://stackoverflow.com/
Slide 15