03 Part1 TemplateDrivenForms
03 Part1 TemplateDrivenForms
Template-Driven Forms
1
Form object in Angular
HTML Typescript
{
<form>
value: {
<label for="name">Name</label>
name: 'Sofie',
<input type="text" id="name"
email: '[email protected]'
name="name" />
}
<label for="email">Email</label>
<input type="text" id="email"
valid: true
name="email" />
}
<button type="submit">Save</button>
</form>
Name Sofie
Email [email protected]
2
2 types of forms in Angular
• Template-Driven:
− form object is created by Angular based on the DOM
− handy to create forms quickly
• Reactive:
− structure of the form is defined in typeScript code
− link HTML and TypeScript manually
− more control options, more fine-tuning
3
Template-Driven form
app.module.ts
4
Select controls
5
Form submit
• No action or method in form tag because direct sending to backend not wanted!
(SPA) => use the JavaScript onSubmit event ngSubmit
• local reference #f => form can be accessed in HTML
• #f = "ngForm" => set ngForm directive to keep track of form value and validity
=> pass form information to TypeScript using f as argument
6
TypeScript: form object
7
Form submit (@Viewchild)
8
Form validation: built-in validator directives
9
Form validation: built-in validator directives
10
Form validation: disable submit button
11
Form validation: CSS classes
12
Validation error messages
13
Default values for form controls
14
Group form controls: ngModelGroup
15
Group form controls: ngModelGroup
16
Set value of input fields without two-way
binding
Overwrite complete form at once
17
Set value of input fields without two-way
binding
18
Assignment
• Create a registration form with at least the following fields:
− name and first name => mandatory, grouped into fullName and name must have at
least 4 letters
− gender using radio buttons => mandatory
− date of birth => mandatory and must be a date
− email => mandatory and must be email
− payment method via dropdown (visa, mastercard or bancontact) with visa as default value
• Use CSS to clarify whether the data entered is right or wrong. Also display error
messages for any wrong input or wrong input group.
• Make sure that submission is possible only if the form is filled in correctly
• After submit, you show an overview of the values entered in your HTML page and
you reset the form (beware of the default value for the payment method!)
19
20