2017-03-12 3 views
0

は、私はシンプルな角度FormBuilderフォームを持っている原因:は、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.subscribeの別の実行を引き起こし、無限ループ実行を受けます(最大呼び出しスタックサイズがを超えました)。どうすればそれを避けることができますか?その場でフォームの値を変更するより良い方法はありますか?

答えて

2

私はあなたがこのために探していると思います:

this.form.patchValue({ count: diff }, { emitEvent: false }); 

この方法valueChangeは私がそうするならば、文句を言わない私のテンプレートが新しいで更新され

Plunker Example

+0

を解雇されることはありませんカウント値だと思います。 – dease

+0

試しましたか?わたしにはできる – yurzui

関連する問題