Search code examples
htmlangularangular8angular-reactive-formsdefault-value

How to take default value in Reactive Form


I want to Pass default value from HTML to Type script using reactive Form

<ul class="list list_2">
<li>Subtotal <span>{{cartTotal | currency:'INR':true:'2.0'}}</span></li>
<li>Shipping Charge<span>{{shipping | currency:'INR':true:'2.0'}}</span></li>
<li>Total <span><input type="text" value="{{cartTotal+shipping | currency:'INR':true:'2.0'}}" class="total" formControlName="TotalAmount" readonly></span></li>
</ul>

This is my HTML where i have given default value in input

get TotalAmount(){
    return this.billingForm.get("TotalAmount.value")

In type script i have this method for getting data and i am using Formgroup

billingForm=new FormGroup({
    Address:new FormControl('',[Validators.required]),
    City:new FormControl('',[Validators.required]),
    State:new FormControl('',[Validators.required]),
    Postcode:new FormControl('',[Validators.required]),
    TotalAmount:new FormControl(''),
    PayType:new FormControl('')
  })

I want to pass that default value but it always giving null


Solution

  • You should wrap things differently.

    First, change your form's initialization.

    Add FormBuilder as a dependency to your component's consctructor.

    constructor(private builder: FormBuilder) {}
    

    And use the builder to initialize your form.

        this.billingForm = this.builder.group({
          Address: new FormControl("", [Validators.required]),
          City: new FormControl("", [Validators.required]),
          State: new FormControl("", [Validators.required]),
          Postcode: new FormControl("", [Validators.required]),
          TotalAmount: new FormControl(""),
          PayType: new FormControl("")
        });
    

    Then, your TotalAmount's HTML as:

    <li>Total <span><input type="text" value="{{TotalAmount | currency:'INR':true:'2.0'}}" class="total" formControlName="TotalAmount" readonly></span></li>
    

    So, when you are getting cartTotal from your db. Assign cartTotal+shipping to your TotalAmount FormControl. Like:

    this.billingForm.get("TotalAmount").setValue(this.cartTotal + this.shipping);
    

    And, change your TotalAmount property as:

       get TotalAmount() {
          return this.billingForm.get("TotalAmount").value;
       }
    

    Sample:

    enter image description here

    Working demo at StackBlitz