Reputation: 986
I am quite new to Angular2 and I am trying to create a reactive form. E.g. I am trying to create an interactive date input.
My HTML:
<div class="date ui-input">
<input type="text" name="dateD" [ngModel]="model.date | date:'dd'" (blur)="setDate($event.target.value, 'd')" maxlength="2" />
<div>.</div>
<input type="text" name="dateM" [ngModel]="model.date | date:'MM'" (blur)="setDate($event.target.value, 'm')" maxlength="2" />
<div>.</div>
<input type="text" name="dateY" [ngModel]="model.date | date:'y'" (blur)="setDate($event.target.value, 'y')" maxlength="4" />
</div>
And the corresponding TypeScript for setDate():
setDate(input:number, type:string[1]) {
let min = 1;
let max = 1;
let fn = null;
switch(type) {
case 'd':
max = 31;
fn = 'setDate';
break;
case 'm':
input -= 1;
min = 0;
max = 11;
fn = 'setMonth';
break;
case 'y':
min = 1990;
max = 9999;
fn = 'setFullYear';
break;
}
if(input < min) {
input = min;
}
else if(input > max) {
input = max;
}
if(fn)
this.model.date[fn](input);
console.log(this.model.date);
}
The model is updating fine, I am checking that with console.log()
. The view is not updating.
I was hoping that the input fields would show the correct date, as per date
-pipe, but seems I am wrong. In Angular 1.x everything was much different, I understand, but yet I was able to achieve my goal.
Any suggestions? Is there maybe a function to "manually" update the model?
Upvotes: 2
Views: 1029
Reputation: 10713
You are trying to directly manipulate the value property of your form field. This doesn't trigger the update. Instead, use patchValue
https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html
$event.target.patchValue({dateY: value});
For example I use it like this in my html:
<form [formGroup]="myForm">
<input formControlName="myValue" (ionChange)="recalculate($event)">
</form>
In my TS code:
public recalculate(e) {
let currentValue = this.myForm.controls.get(myValue).value;
this.myForm.patchValue({ myValue: currentValue / 10 });
}
Upvotes: 3