Lab 13 - Template Driven Forms
Intro
In this lab we will create a form to allow a user to be added to the system
1. Create a new component and add it to the menu / navigation
-
Create a component to create a user
-
Add a route to display the new user component, and a menu link.
2. Create a form to add in a new user
- In the HTML create the following HTML form:
<h2>New User</h2>
<form>
<label for="firstname">First name:</label>
<input id="firstname" name="firstname" type="text" />
<label for="surname">Surname:</label>
<input id="surname" name="surname" type="text" />
<button type="submit">Add User</button>
</form>
and create some basic css styling:
form {
display: flex;
flex-direction: column;
width: 300px;
}
label {
margin-bottom: 5px;
}
input {
margin-bottom: 10px;
}
- In the typescript, create 2 variables to store the data for the fields on the form
Click here to see the sample solution
firstname: string = '';
surname: string = '';
- Bind the fields to the form with NgModel. You'll also need to import
FormsModuleinto the imports section of the @Component decorator.
Click here to see the sample solution
<input id="firstname" name="firstname" type="text" [(ngModel)]="firstname" />
...
<input id="surname" name="surname" type="text" [(ngModel)]="surname" />
- Create a function to handle the submit event of the form - for now console.log the values of the variables
Click here to see the sample solution
onSubmit() {
console.log(`New user created: ${this.firstname} ${this.surname}`);
}
- Bind the onSubmit function to the submit event of the form.
Click here to see the sample solution
<form (submit)="onSubmit()">
- Test this in your browser.
2. Styles and validation
- Make both fields required fields
Click here to see the sample solution
<input id="firstname" name="firstname" type="text" [(ngModel)]="firstname" required />
...
<input id="surname" name="surname" type="text" [(ngModel)]="surname" required />
- define css rules to highlight the field in red if it has been edited and is not valid
Click here to see the sample solution
input.ng-invalid.ng-touched {
border: 1px solid red;
}