Reputation: 5986
I need perform a manipulation on a string that is changing by the user on a textarea
control.
the problem is that the 2 way binding [(ngModel)]
,keypress
and also paste
events raised before the control is updating.
for example, look at the console output, when the char 's' is appended (via keyboard or paste it) that is the aftermath:
then when adding another 's', the function catches
the previous result and not the current result and another 's' is missed.
I am very new to angular and front end web development, maybe i am missing something(?)
how can i overcome that problem?
here is a summarized parts of my code, HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div class="txtAr txtleft">
<textarea rows="1" class="txt" id="txtLft" [(ngModel)]="LeftText" (keypress)="c()" (paste)="c()"></textarea>
</div>
</body>
</html>
TypeScript (test) class:
export class TxtZoneComponent {
public LeftText: string = "enter your string"
public RightText: string = "enter your string"
public c(): void
{
let inputValue = (document.getElementById("txtLft") as HTMLInputElement).value;
console.log("paste and kepress events: " + inputValue);
console.log("2 way binding: " + this.LeftText);
}
}
Upvotes: 3
Views: 7638
Reputation: 12552
This is probably happening due to the order in which the events are triggered by the input control (input, keypress, etc.) Since two way binding with ngModel is just syntactic sugar you can separate the property binding and the event handler:
<textarea [value]="LeftText" (input)="c($event.target.value)"></textarea>
And in the event handler manually assign the value to the local property and do any other processing you might need:
c(value: string) {
this.LeftText = value;
console.log(this.LeftText);
// any additional things you want to do
}
This will also make your code a bit cleaner since you won't need to manually handle any other events.
Upvotes: 2