How To Set Value In Template-Driven Forms In Angular
In this article, we will learn how to set values in template-driven forms in Angular. We will learn how to set form control default or starting values, dynamically set values, and reset the form value, among other things. Learn how to change the value of a single FormControl, a FormGroup, or a nested FormGroup.
Template
The app.component.html file from the angular template-driven forms article is shown below.
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)"> <p> <label for="firstname">First Name </label> <input type="text" id="firstname" name="firstname" ngModel> </p> <p> <label for="lastname">Last Name </label> <input type="text" id="lastname" name="lastname" ngModel> </p> <p> <label for="email">Email </label> <input type="text" id="email" name="email" ngModel> </p> <p> <label for="gender">Geneder </label> <input type="radio" value="male" id="gender" name="gender" ngModel> Male <input type="radio" value="female" id="gender" name="gender" ngModel> Female </p> <p> <label for="isMarried">Married </label> <input type="checkbox" id="isMarried" name="isMarried" ngModel> </p> <p> <label for="country">country </label> <select id="country" name="country" ngModel> <option [ngValue]="c.id" *ngFor="let c of countryList"> {{c.name}} </option> </select> </p> <div ngModelGroup="address"> <p> <label for="city">City</label> <input type="text" id="city" name="city" ngModel> </p> <p> <label for="street">Street</label> <input type="text" id="street" name="street" ngModel> </p> <p> <label for="pincode">Pin Code</label> <input type="text" id="pincode" name="pincode" ngModel> </p> </div> <p> <button type="submit">Submit</button> </p> </form>
It is preferable to build a model class for the above form before setting the default value. Add the following class to the app.component.ts file.
export class contact { firstname:string; lastname:string; email:string; gender:string; isMarried:boolean; country:string; address: { city:string; street:string; pincode:string; } }
Set value in template-driven forms
The value of the form components can be set in two ways.
- Two-way data binding.
- Use the template variable reference.
Two-way data binding
In template-driven forms, two-way data binding is the recommended method for setting the value.
The [(ngModel)]="contact.firstname" attribute is used in the following code to bind the firstname HTML element to the contact.firstname field in the component class. Any changes made to the form are automatically propagated to the component class, and chan ges to the component class are immediately visible in the form.
<label for="firstname">First Name </label> <input type="text" id="firstname" name="firstname" [(ngModel)]="contact.firstname">
Set the default/initial value
All you have to do to specify the initial or default value is create the contact model in the ngOnInit method, as seen below.
ngOnInit() { this.contact = { firstname: "Sachin", lastname: "Tendulkar", email: "sachin@gmail.com", gender: "male", isMarried: true, country: "2", address: { city: "Mumbai", street: "Perry Cross Rd", pincode: "400050" } }; }
Set the value individually or dynamically
changeCountry() { this.contact.country = "1"; }
Reset form
<button type="button" (click)="reset(contactForm)">Reset</button>
reset(contactForm :NgForm) { contactForm.resetForm(); }
Now, add the following code into the app.component.ts file.
import { Component, ViewChild, ElementRef, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Template driven forms'; countryList: country[] = [ new country("1", "India"), new country('2', 'USA'), new country('3', 'England') ]; contact: contact; ngOnInit() { this.contact = { firstname: "Sachin", lastname: "Tendulkar", email: "sachin@gmail.com", gender: "male", isMarried: true, country: "2", address: { city: "Mumbai", street: "Perry Cross Rd", pincode: "400050" } }; } onSubmit() { console.log(this.contact); } setDefaults() { this.contact = { firstname: "Sachin", lastname: "Tendulkar", email: "sachin@gmail.com", gender: "male", isMarried: true, country: "2", address: { city: "Mumbai", street: "Perry Cross Rd", pincode: "400050" } }; } changeCountry() { this.contact.country = "1"; } reset(contactForm :NgForm) { contactForm.resetForm(); } } export class contact { firstname: string; lastname: string; email: string; gender: string; isMarried: boolean; country: string; address: { city: string; street: string; pincode: string; } } export class country { id: string; name: string; constructor(id: string, name: string) { this.id = id; this.name = name; } }
Open the app.component.html file and add the following code.
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)"> <p> <label for="firstname">First Name </label> <input type="text" id="firstname" name="firstname" [(ngModel)]="contact.firstname"> </p> <p> <label for="lastname">Last Name </label> <input type="text" id="lastname" name="lastname" [(ngModel)]="contact.lastname"> </p> <p> <label for="email">Email </label> <input type="text" id="email" name="email" [(ngModel)]="contact.email"> </p> <p> <label for="gender">Geneder </label> <input type="radio" value="male" id="gender" name="gender" [(ngModel)]="contact.gender"> Male <input type="radio" value="female" id="gender" name="gender" [(ngModel)]="contact.gender"> Female </p> <p> <label for="isMarried">Married </label> <input type="checkbox" id="isMarried" name="isMarried" [(ngModel)]="contact.isMarried"> </p> <p> <label for="country">country </label> <select id="country" name="country" [(ngModel)]="contact.country"> <option [ngValue]="c.id" *ngFor="let c of countryList"> {{c.name}} </option> </select> </p> <div ngModelGroup="address"> <p> <label for="city">City</label> <input type="text" id="city" name="city" [(ngModel)]="contact.address.city"> </p> <p> <label for="street">Street</label> <input type="text" id="street" name="street" [(ngModel)]="contact.address.street"> </p> <p> <label for="pincode">Pin Code</label> <input type="text" id="pincode" name="pincode" [(ngModel)]="contact.address.pincode"> </p> </div> <p> <button type="submit">Submit</button> </p> <p> <button type="button" (click)="changeCountry()">Change Country</button> <button type="button" (click)="setDefaults()">Set Defaults</button> <button type="button" (click)="reset(contactForm)">Reset</button> </p> <b>valid</b> {{contactForm.valid}} <b>touched</b> {{contactForm.touched}} <b>pristine</b> {{contactForm.pristine}} <b>dirty</b> {{contactForm.dirty}} </form>
Template reference variable
We have a reference variable called #contactForm that is an instance of ngForm.
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
Using the viewChild, we can get the reference to the #contactForm in app.component.ts.
@ViewChild('contactForm',null) contactForm: NgForm;
We can use the setValue method of the ngForm to set the initial value once we obtain the reference.
Set the default or initial value
ngOnInit() { this.contact = { firstname: "Sachin", lastname: "Tendulkar", email: "sachin@gmail.com", gender: "male", isMarried: true, country: "2", address: { city: "Mumbai", street: "Perry Cross Rd", pincode: "400050" } }; setTimeout(() => { this.contactForm.setValue(this.contact); }); }
It's worth noting that we're employing the setTimeout command. Because the form controls have not yet been initialized when OnInit is called, this is the case. The following error message will appear.
Set the value individually or dynamically
You may also use the setValue method of the specific FormControl to set the value.
The specific FormControl reference may be found in the ngForm's controls collection. To modify the value, use the setValue method on the FormControl instance once you've obtained the reference.
This code, for example, will change the nation to India.
changeCountry() { this.contactForm.controls["country"].setValue("1"); }
From the Template, call the changeCountry method.
<button type="button" (click)="changeCountry()">Change Country</button>
Reset values
The ngForm's reset or resetForm methods can be used to reset the form to an empty value. These also reset the status of the form, such as filthy, valid, immaculate, and touched, among others.
reset() { this.contactForm.reset(); } resetForm() { this.contactForm.resetForm(); }
Set Default Value
You can use setValue to return the form to its default value at any moment. This will set the entire form to the contact form's value.
setDefaults() { this.contactForm.setValue(this.contact); }
patch value
PatchValue can be used to change only a few fields at a time. The ngForm's control property delivers a reference to the top-level FormGroup. The patchValue method can then be used to update only the firstname, lastname, and email fields.
patchValue() { let obj = { firstname: "Rahul", lastname: "Dravid", email: "rahul@gmail.com", }; this.contactForm.control.patchValue(obj); }
Set value of nested FormGroup
You may change the nested FormGroup by gaining a reference to it from the ngForm controls collection.
changeAddress() { let obj = { city: "Bangalore", street: "Brigade Road", pincode: "600100" }; let address= this.contactForm.controls["address"] as FormGroup address.patchValue(obj); }
The complete code of the app.component.ts file
import { Component, ViewChild, ElementRef, OnInit } from '@angular/core'; import { NgForm, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Template driven forms'; @ViewChild('contactForm', null) contactForm: NgForm; countryList: country[] = [ new country("1", "India"), new country('2', 'USA'), new country('3', 'England') ]; contact: contact; ngOnInit() { this.contact = { firstname: "Sachin", lastname: "Tendulkar", email: "sachin@gmail.com", gender: "male", isMarried: true, country: "2", address: { city: "Mumbai", street: "Perry Cross Rd", pincode: "400050" } }; setTimeout(() => { this.contactForm.setValue(this.contact); }); } onSubmit() { console.log(this.contactForm.value); } setDefaults() { this.contactForm.setValue(this.contact); } changeCountry() { this.contactForm.controls["country"].setValue("1"); } patchValue() { let obj = { firstname: "Rahul", lastname: "Dravid", email: "rahul@gmail.com", }; this.contactForm.control.patchValue(obj); } changeAddress() { let obj = { city: "Bangalore", street: "Brigade Road", pincode: "600100" }; let address= this.contactForm.controls["address"] as FormGroup address.patchValue(obj); } reset() { this.contactForm.reset(); } resetForm() { this.contactForm.resetForm(); } } export class contact { firstname: string; lastname: string; email: string; gender: string; isMarried: boolean; country: string; address: { city: string; street: string; pincode: string; } } export class country { id: string; name: string; constructor(id: string, name: string) { this.id = id; this.name = name; } }
The complete code of the app.component.html file.
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)"> <p> <label for="firstname">First Name </label> <input type="text" id="firstname" name="firstname" ngModel> </p> <p> <label for="lastname">Last Name </label> <input type="text" id="lastname" name="lastname" ngModel> </p> <p> <label for="email">Email </label> <input type="text" id="email" name="email" ngModel> </p> <p> <label for="gender">Geneder </label> <input type="radio" value="male" id="gender" name="gender" ngModel> Male <input type="radio" value="female" id="gender" name="gender" ngModel> Female </p> <p> <label for="isMarried">Married </label> <input type="checkbox" id="isMarried" name="isMarried" ngModel> </p> <p> <label for="country">country </label> <select id="country" name="country" ngModel> <option [ngValue]="c.id" *ngFor="let c of countryList"> {{c.name}} </option> </select> </p> <div ngModelGroup="address"> <p> <label for="city">City</label> <input type="text" id="city" name="city" ngModel> </p> <p> <label for="street">Street</label> <input type="text" id="street" name="street" ngModel> </p> <p> <label for="pincode">Pin Code</label> <input type="text" id="pincode" name="pincode" ngModel> </p> </div> <p> <button type="submit">Submit</button> </p> <p> <button type="button" (click)="changeCountry()">Change Country</button> <button type="button" (click)="setDefaults()">Set Defaults</button> <button type="button" (click)="patchValue()">Patch Value</button> <button type="button" (click)="changeAddress()">Change Address</button> <button type="button" (click)="reset()">Reset</button> <button type="button" (click)="resetForm()">Reset Form</button> </p> <b>valid</b> {{contactForm.valid}} <b>touched</b> {{contactForm.touched}} <b>pristine</b> {{contactForm.pristine}} <b>dirty</b> {{contactForm.dirty}} </form>
In this article, we covered how to set the form values in template-driven forms. We can use either the ngForm directive's setValue or the two-way data binding.
I hope this article helps you and you will like it.👍
If you have any doubt or confusion then free to ask in comment section.