根据 Angular 4 中下拉列表中的值更改日期

Changing Date Based From Value in Dropdown in Angular 4

我有这个付款期限,它是一个下拉菜单。该付款期限具有价值。所以我需要从当前日期开始添加这些值,以便我可以显示它。下面是我的代码。

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>

Have a look at the following - using Vanilla JS

Demo

Cleaner Approach - using moment.js

Demo

Solution

  1. 彻底使用响应式表单
  2. 无需使用(ngModelChange)="onSelectPaymentTerm($event)"。但这不是问题
  3. 所选值以字符串形式出现,因此在添加到日期之前必须使用 parseInt 将其转换为整数
  4. 在 Javascript
  5. 中更喜欢 Moment.js 进行日期操作