How to use NgForm with template Variables In Angular
Let’s consider an example where we’ll create a template variable called “userForm” referring to the Angular’s NgForm directive instance. We’ll check the validity of the form and then display a message accordingly.
<!-- app.component.html !-->
<h2>w3wiki</h2>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" ngModel required />
<label for="age"Age></label>
<input type="number" name="age" id="age" ngModel required />
<button type="submit">Submit</button>
</form>
<div [hidden]="!userForm.form.valid">
<p>My name is {{name}} and I'm {{age}} years old.</p>
</div>
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name: string = '';
age: number = 0;
onSubmit(form: any) {
this.name = form.value.name;
this.age = form.value.age;
}
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
Output:
Understanding Templates Variable in Angular
Template variables in Angular allow us to use the data from one part of the template to another part of the same template. There are various use cases where these template variables come in handy. For example, responding to the user input or responding to the form submission.
In this article, we’ll explore what are template variables and how to use them.
Table of Content
- What are Template Variables?
- Syntax for Declaring Template Variables
- Scope of Template Variables
- DOM Element Template Variable
- Using NgForm with template Variables
Contact Us