Reputation: 9765
I have a text field that I am trying to read the value from when it is changed. After I modify the field (by removing characters) I keep getting undefined, although the event does fire as expected. What am I doing wrong here?
Result of the code below:
changed: {"isTrusted":true} undefined
View:
....
<ng-container matColumnDef="email">
<mat-header-cell *matHeaderCellDef> Email </mat-header-cell>
<mat-cell *matCellDef="let e">
<mat-form-field floatLabel="never">
<input matInput placeholder="no email" (change)="emailUpdated($event)" [value]="e.email" [(ngModel)]="e.email">
</mat-form-field>
</mat-cell>
</ng-container>
....
in my component:
emailUpdated(event) {
console.log('changed: '+JSON.stringify(event)+' '+event.email);
}
Upvotes: 0
Views: 11100
Reputation: 73731
You can get the updated value in the handler of the change
event with event.target.value
:
<input [(ngModel)]="e.email" (change)="emailUpdated($event)" ... >
emailUpdated(event) {
console.log("New email", event.target.value);
}
You could also simply use e.email
, since it is bound to the input element with [(ngModel)]
:
emailUpdated() {
console.log("New email", this.e.email);
}
As an alternative, if you want to be notified as the value is being modified (on each key stroke), handle the ngModelChange
event:
<input [(ngModel)]="e.email" (ngModelChange)="emailUpdated($event)" ... >
In that case, the $event
parameter is the updated value:
emailUpdated(value) {
console.log("New email", value);
}
Note: you don't need to bind [value]
since you are using two way data binding.
Upvotes: 3