i具有3个字段的简单角形式构成形式(在离子2应用中):
constructor(public navCtrl: NavController, public navParams: NavParams,
public viewCtrl: ViewController, private builder: FormBuilder) {
this.form = this.builder.group({
startDate: ['', Validators.required],
endDate: ['', Validators.required],
count: [0, Validators.required], //diff in days
});
}
我的模板:
<ion-item>
<ion-label floating>Start</ion-label>
<ion-datetime formControlName="startDate" [min]="today_iso" displayFormat="DD/MM/YYYY" pickerFormat="DD/MM/YYYY">
</ion-datetime>
</ion-item>
<ion-item>
<ion-label floating>End</ion-label>
<ion-datetime formControlName="endDate" [min]="today_iso" displayFormat="DD/MM/YYYY" pickerFormat="DD/MM/YYYY">
</ion-datetime>
</ion-item>
<ion-item>
<ion-label fixed>Count</ion-label>
<ion-input type="number" formControlName="count" ></ion-input>
</ion-item>
我想使用Moment.JS动态计算两个日期之间的差异,然后修改计数字段的形式值:
this.form.valueChanges.subscribe(data => {
let startDate = moment(data.startDate);
let endDate = moment(data.endDate);
let diff = endDate.diff(startDate, 'days');
if(diff>0) {
this.form.patchValue({
count: diff
})
}
});
然而,似乎是form.patchValue导致valuechanges的另一个执行。我该怎么避免?是否有更好的方法可以随时修改形式值?
我想您正在寻找这个:
this.form.patchValue({ count: diff }, { emitEvent: false });
这样就不会触发 valueChange
plunker示例