Home > other >  pass value from one method to another in angular 13
pass value from one method to another in angular 13

Time:04-09

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 => {
 
    });
  }

CodePudding user response:

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 :)

CodePudding user response:

Start with basics: https://www.typescriptlang.org/docs/handbook/classes.html

You need to use a class member:

selectedOption: string;

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


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