I created a custom function inside a class, how do I call it within the same class?
A user enters a word in an input field. It triggers the "onNameKeyUp" function below. I have to verify if the word is plural: if yes I turn it into a singular form. I am giving below a very simplified example:
export class HomeComponent implements OnInit {
spelling="";
tokenizeSpellingEnglish(item: string): string{
if (item =="houses"){
item = "house";
}
return item;
}
onNameKeyUp(event: any){
this.spelling = event;
this.spelling = this.spelling.toLowerCase();
this.tokenizeSpellingEnglish(this.spelling);
this.elem.nativeElement.focus();
}
The singular form will then be sent to the server for further processing.
the application works fine without the spelling verification.
As a side note, I am wondering if this is the right approach at all: should I parse the user input on the server instead? That being said, still I would love to know what is wrong with the above code.
If I understand you correctly, and your example code is truly representative of your real code, I see that you are calling tokenizeSpellingEnglish
but never storing the returned value back into this.spelling
:
export class HomeComponent implements OnInit {
spelling="";
tokenizeSpellingEnglish(item: string): string{
if (item =="houses"){
item = "house";
}
return item;
}
onNameKeyUp(event: any){
this.spelling = event;
this.spelling = this.spelling.toLowerCase();
// --> this.tokenizeSpellingEnglish(this.spelling); should be
this.spelling = this.tokenizeSpellingEnglish(this.spelling);
this.elem.nativeElement.focus();
}
You could also have tokenizeSpellingEnglish
work directly on this.spelling, if that suits your use case.
If your code is instead simply failing to execute properly, I'd look at how you are unpacking the event parameter in onNameKeyUp
. If you are handling the raw event object from the 'keyup' event, you need to get the value from the target
property on the event object and work with that:
onNameKeyUp(event: any) {
this.spelling = event.target.value;
// the rest of your function as before
}
HTH
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments