Angular
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
Include header component in app component html and include a mat-
tab grouping from
Common_Angular_Material_Structures_And_Options document in
Angular References and include the forms 2 components in the 2 different
tabs with labels "Template-Driven Forms" and "Reactive Forms"
Slide 2
Because Angular is a Single-page application, you do not submit
form data to the server as you might in another application.
All form setup and validation is done in Angular and then we will
look at sending to the server using HTTPS
There are 2 approaches to working with forms in Angular
Template-driven approach: HTML form is created and Angular
HTML
Form infers (deduces) the structure of the form
Approaches
Used for more simple forms
Reactive approach: structure is defined in code; form is setup
in HTML and then both are manually connected; this approach
provides greater control
Used for more complex form setups
Slide 3
FormsModule must be imported for forms to work (should have
been included during default setup)
With template-driven approach, the <form> tag tells Angular to
automatically create the template ONCE we register control of each
field
Template
We do NOT include "action" or "method" in the <form> tag
Driven
Forms To do this, we include ngModel to tell Angular which fields are
controls
ngModel control established-no binding
[ngModel] one-way control-used to set a default value
[(ngModel)] 2-way binding-update output value
Slide 4
Building our form
From formsApp.txt in SLATE, copy in the basic structure provided for
template-forms-component.html AND template-forms-
component.css AND template-forms-component.ts
In the first 2 mat-form-field areas under <mat-label> include an input
box to which will hold entry of first name and last name
<input matInput id="first"> <input matInput id="last">
Template
In the <mat-radio-group> Include 2 mat-radio-button fields setting the
Driven
value of the first to "brampton" and the second to "other"
Forms <mat-radio-button value="brampton">
Brampton</mat-radio-button>
In the <mat-select> field, use an *ngFor to create <mat-option> fields
for all campuses in the campuslist
<mat-option *ngFor="let x of campuslist"
[value]="x">{{x}}</mat-option>
Slide 5
Each control field MUST be specified individually
Include for control fields ngModel name="identifying name"
<input matInput id="first" ngModel name="first">
Update all fields (first, last, radio group and select) accordingly to specify
field as a control group ngModel and include 'name= control field
identifying name' for each ('first', 'last', 'city', 'campus')
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)>
Update TypeScript and include NgForm import AND onSubmit function
import {NgForm} from '@angular/forms';
onSubmit(form: NgForm) { console.log(form); }
Template Click the Submit button and then look in the console; you should see the
Driven instance of ngForm
Forms
Expand NgForm in the console and then expand form: FormGroup
controls: Shows each control field and current state
status: Valid values entered based on validators included
touched: form has been altered
value: Quick view of control field values
Slide 7
Validation (will look similar to HTML forms)
Example: required
Include required on BOTH the first name and last name
control fields AND #first="ngModel" for first field AND
#last="ngModel" for last field so access is available to the
control field information
<input matInput id="first" ngModel name="first"
Template
required #first="ngModel">
Driven
Notice the * that shows up in the input box
Forms
Note: If an 'Error: NG0500 or NG0502: …Hydration error…
Stop the serve and re-serve
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>
Both conditions are being check through the ngForm instance
Note: MUST click into field before clicking Submit to test
Slide 9
Conditions can be added to the submit button also
Disable button using property binding until all fields are valid
(ngForm instance is valid)
On submit button [disabled]='!f.valid' added to submit button
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
This type of approach provided greater control and is used for
larger and more complex forms
Reactive
Copy the form layout from formsApp.txt to
Forms
reactive-forms.component.html
Copy the .css and .ts from formsApp.txt to
reactive-forms.component.css and
reactive-forms.component.ts
NOTE: Make sure ReactiveFormsModule has been imported into
app.module.ts (which is part of our default setup)
Slide 11
Open reactive-forms.component.ts
For reactive forms to work, imports must be included from angular/forms
Import {FormGroup, FormControl} from '@angular/forms';
Next, a form name variable must be set to FormGroup data type which
will be used to pull together all control fields by name into this one object
sheridanForm!: FormGroup;
Reactive
Forms Using ngOnInit() LifeCycle Hook, create the form controls
ngOnInit() {
this.sheridanForm = new FormGroup({
'idnumber': new FormControl(null),
'login' : new FormControl(null),
'campus': new FormControl('Davis')
}); }
Notice 'campus' default set within FormControl
Slide 12
Each form field needs to be identified using the same name as
setup in the ngOnInit() (idnumber, login, campus)
Ex. <input matInput formControlName="idnumber">
To setup submit
<form [formGroup]="sheridanForm" (ngSubmit)="onSubmit()">
Reactive In .ts, create the function to display FormGroup in console
onSubmit() { console.log(this.sheridanForm); }
Forms
This approach does NOT need a local reference as discussed in the
template driven approach
Testing:
Bring up form and click Submit button
Check in Console and open FormGroup
Slide 13
Validators https://angular.io/api/forms/Validators
Look at the validators available in Angular by opening the link
Validators must also be imported before using
import {…, Validators} from '@angular/forms';
Update FormControl (ex. shown for idnumber only)
Reactive
'idnumber': new FormControl(null, Validators.required),
Forms
A message can be added similar to template-drive approach to
give user more specifics (after <input>)
<span *ngIf="!sheridanForm.get('idnumber')!.valid &&
sheridanForm.get('idnumber')!.touched">
This field is required</span>
Will have to take into account strict syntax (notice ! before .valid and .touched)
Slide 14
https://angular.dev/
https://angular.dev/overview
Sources https://nodejs.org/en/
https://docs.npmjs.com/
https://help.github.com/en
https://stackoverflow.com/
Slide 15