ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

How to set value in template-driven forms in Angular

In this tutorial, we will learn how to set value in template-driven forms in Angular. We will learn how to set the default or initial value to form controls, dynamically set values, reset the value of the form, etc. Learn how to set the value of individual FormControl or a FormGroup and nested FormGroup.

We have covered how to create template-driven forms in the angular tutorial.We will continue from there and in this tutorial, we will show you

Template

The following is the app.component.html from the angular template-driven forms tutorial.

                              
 
<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>
 
                            
                        

Before we set the default value, it is better to create a model class for the above form. Open the app.component.ts and add the following class

                              
 
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

There are two ways you can set the value of the form elements

  • Two-way data binding
  • Use the template reference variable
  • Two-way data binding

    The two-way data binding.is the recommended way to set the value in the template-driven forms.

    The following code uses the [(ngModel)]="contact.firstname" to bind the firstname HTML element to the contact.firstname field in the component class. The advantageous here is that any changes made in the form are automatically propagated to the component class and changes made in component class are immediately shown in the form.

                                  
    
    <label for="firstname">First Name </label>
    <input type="text" id="firstname" name="firstname" [(ngModel)]="contact.firstname">
                                
                            

    Set the default/initial value

    To set the initial or default value all you need to populate the contact model in the ngOnInit method as shown 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();
    }
                                
                            

    [tabby title=”app.component.ts”]

                                  
    
    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;
      }
    }
                                
                            

    [tabby title=”app.component.html”]

                                  
    
    <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>
     
                                
                            

    [tabbyending]

    Template reference variable

    We have a #contactForm reference variable, which is an instance of ngForm.

                                  
     
    <form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
                                
                            

    We can get the reference to the #contactForm in the app.component.ts, using the viewchild

                                  
    
     @ViewChild('contactForm',null) contactForm: NgForm;
                                
                            

    Once we have the reference, we can use the setValue method of the ngForm to set the initial value

    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);
        });
     
      }
     
                                
                            

    Note that we are using the setTimeout That is because the form controls are yet initialized when the OnInit is fired. We will get the following error message

    image

    Set the value individually or dynamically

    You can also set the value individually using the setValue method of the individual FormControl.

    You will get the reference to the individual FormControl from the controls collection of the ngForm. Once you get the reference use the setValue on the FormControl instance to change the value.

    For Example, this code will change the country to India

                                  
    changeCountry() {
       this.contactForm.controls["country"].setValue("1");
    }
                                
                            

    Call the changeCountry method from the Template.

                                  
    
    <button type="button" (click)="changeCountry()">Change Country</button>
                                
                            

    Reset values

    You can reset the form to empty value using the reset or resetForm method of the ngForm. These also resets the form status like dirty,valid,pristine & touched, etc

                                   
    reset() {
      this.contactForm.reset();
    }
     
                                
                            
                                  
     
    resetForm() {
       this.contactForm.resetForm();
    }
     
                                
                            

    Set Default Value

    You can invoke the setValue anytime to set the form back to the default value. This will set the entire form to the value held by the contact form.

                                  
    
     setDefaults() {
        this.contactForm.setValue(this.contact);
      }
     
                                
                            

    patch value

    You can make use of the patchValue to change the only few fields anytime. The control property of the ngForm returns the reference to the top level FormGroup. Then, you can make use of the patchValue method to change only firstname,lastname & email fields

                                  
    
      patchValue() {
        let obj = {
          firstname: "Rahul",
          lastname: "Dravid",
          email: "rahul@gmail.com",
        };
     
        this.contactForm.control.patchValue(obj);
     
      }
     
                                
                            

    Set value of nested FormGroup

    You can update nested FormGroup by getting a reference to the nested FormGroup from the controls collection of ngForm.

                                  
     
      changeAddress() {
        let obj = {
          city: "Bangalore",
          street: "Brigade Road",
          pincode: "600100"
        };
        let address= this.contactForm.controls["address"] as FormGroup
        address.patchValue(obj);
     
      }
                                
                            
    The complete code.

    [tabby title=”app.component.ts”]

                                  
    
    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;
      }
    }
                                
                            

    [tabby title=”app.component.html”]

                                  
    
     
    <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>
     
     
                                
                            

    [tabbyending]

    image