Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pass value from one method to another in angular 13

I need to use the value from an onchange event from a dropdown menu in angular and will need the transfer of data from method onoptionchange to foo method in angular 13

onOptionChange(value: string) {
    console.log("value is :: ", value);
  }



foo(): void {
    this.service.getinfo({{value }}).subscribe(res => {
 
    });
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use the (change) event binding in the HTML part of angular and add your onOptionChange method to it.

<select class='select-option'
#mySelect
(change)='onOptionChange(mySelect.value)'>
   <option class='option' 
      *ngFor='let option of dropDownData' 
      [value]="option.value"
   >{{option.label}}</option>
</select>

The corresponding JS code can be the same as yours. Just add a line into the onOptionChange function passing the value passed as an argument to the ‘foo’ function.

onOptionChange(value: string): void {
   console.log("value is :: ", value);
   foo(value);
}

foo(value: string): void {
   this.service.getinfo(value).subscribe(res => {
      // enter code here
   });
}

If you don’t want to pass the value as an argument to the foo method you can create a global variable and save the changed value into it and use it inside foo as below:

let selectedValue: string;

onOptionChange(value: string): void {
   console.log("value is :: ", value);
   this.selectedValue = value;
}

foo(): void {
   this.service.getinfo(this.selectedValue).subscribe(res => {
      // enter code here
   });
}

If the explanation helped, please give an upvote 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading