Module 10 - HTML Forms Flashcards
Reactive Forms Import
import { FormGroup, FormControl, Validators } from ‘@angular/forms’;
Reactive Forms Configure
this.sheridanForm = new FormGroup({
‘idnumber’: new FormControl(null, Validators.required),
‘login’: new FormControl(null),
‘campus’: new FormControl(‘Davis’)
});
Reactive Forms Use
<input matInput formControlName="idnumber">`
<input matInput formControlName="login">
```
<input></input>
~~~
<form [formGroup]="sheridanForm" (ngSubmit)="onSubmit()">
Template Driven Forms Import
import { FormsModule } from ‘@angular/forms’;
Template Driven Forms Configure
<input matInput id=”first” ngModel name=”first” required #first=”ngModel”>
Template Driven Forms Use
<form #f=”ngForm” (ngSubmit)=onSubmit(f)”>
What are the two approaches to working with forms in Angular, and when would you use each?
- Template-driven forms: Used for simpler forms, where the structure is inferred from the HTML template.
- Reactive forms: Used for more complex forms, where the form structure is defined in the TypeScript code.
How do you handle form submission in a template-driven form using Angular?
Form submission is handled using the ngSubmit directive and binding it to a function in the component.
Example:
<form #f=”ngForm” (ngSubmit)=”onSubmit(f)”>
What is the role of FormGroup in reactive forms, and how is it used?
FormGroup is used to group form controls in a reactive form, allowing for the management of the form’s overall state. It is defined in the component’s TypeScript file.
Example:
this.sheridanForm = new FormGroup({
‘idnumber’: new FormControl(null, Validators.required),
‘login’: new FormControl(null),
‘campus’: new FormControl(‘Davis’)
});