Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  24] [ 5]  / answers: 1 / hits: 7917  / 4 Years ago, fri, august 7, 2020, 12:00:00

I'm working with a parent and child component. The child component has the input field and will emit the value entered by the user to the parent component like this:


<parent-component (sendInputValue)="getInputValue($event)"><parent-component>

Now in parent component I have this:


getInputField(data){
console.log(data); // this prints the data (Example: abc)
// then here I'm just executing the API call ONLY if data length is 3
if(data.length === 3){
this.myService.getDataFromService(data).subscribe(rs=>console.log(rs));
}
}

Now let's say this happens:



  1. The user enters: abc // API call gets execute that is good

  2. Now, user enters: abcd // No API call gets executed, that is good

  3. Now user deletes letter "d" and the new value of data will be "abc" I DONT want to execute API call again because we already execute API call for "abc"

  4. Now if the user deletes the letter "c" the new value of data is now "ab". At this point, no API call is expected

  5. Now if the user adds the letter "c" the new value will be "abc". At this point, the API call is expected. (this is working)


So how to always execute API call if input data is 3 characters and if the user enters more characters nothing should happen, and if he deletes characters and goes back to the first 3 characters nothing should happen because the API already happened? Thanks a lot in advance!


More From » angular

 Answers
4

Below is the little tweak in your code and it will fulfill the requirement told by you.


You can definitely improve this process using debounce, distinctUntilChanged, switchMap operators.


previousData = '' // create a property which will track of previous data from parent component.

getInputField(data){
if(data && data.length === 3 && data.length > previousData.length){
this.myService.getDataFromService(data).subscribe(rs=>console.log(rs));
}
this.previousData = data || ''; // update previous data to current data after backend call.
}

[#2957] Monday, August 3, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Fri, Feb 12, 21, 00:00, 3 Years ago
Mon, Jun 29, 20, 00:00, 4 Years ago
;