Search code examples
angularangular-reactive-formsangular4-forms

Changing Date Based From Value in Dropdown in Angular 4


I have this payment term that is a dropdown. And that payment term has values. So i need to add those value from the current date so i can display it. Here's my code below.

this.addForm = this.fb.group({
      payment_term: new FormControl(null, Validators.required),
      due_date: new FormControl(null, Validators.required),
});



onSelectPaymentTerm(event){
    console.log(event)
    this.addForm.patchValue({
      due_date: this.date.setDate( this.date.getDate() + event)
    })
  }

HTML

<div class="form-group row">
    <label class="col-sm-3 col-form-label">Payment Term</label>
    <div class="col-sm-9">
        <select type="text" class="form-control" formControlName="payment_term" (ngModelChange)="onSelectPaymentTerm($event)">
            <option value="null" hidden>-- Select Payment Term --</option>
            <option *ngFor="let payment of payments" [value]="payment?.value">{{ payment?.name }}</option>
        </select>
    </div>
</div>

<div class="form-group row">
    <label class="col-sm-4 col-form-label">Due Date</label>
    <div class="col-sm-8">
        <input type="text" class="form-control" formControlName="due_date" readonly>
    </div>
</div>

Solution

  • Have a look at the following - using Vanilla JS

    Demo

    Cleaner Approach - using moment.js

    Demo

    Solution

    1. Use Reactive form through and through
    2. No need to use (ngModelChange)="onSelectPaymentTerm($event)". But this wasn't the problem
    3. Selected value comes as a string, and hence must be converted to integer with parseInt before adding to the date
    4. Prefer Moment.js for date manipulation in Javascript