2

I wrote a function with $event in Angular2 and through click event from template class it's working fine. But I am trying to call that function manually, So for that how to pass a event value through function.

This is my function:

onActionChange($event) {
 // alert($event.target.value);
    const selectedAction = parseInt($event.target.value);
    }

This is how i am trying to call function: onActionChange('7');

Here I am getting error like:

TypeError: Cannot read property 'value' of undefined
Roy
  • 880
  • 7
  • 21
  • 39
  • 6
    Well your function expects an event parameter and you're passing a string to it, so I wonder what could have caused this error message – Phiter Aug 30 '18 at 14:45
  • https://stackoverflow.com/questions/37944199/what-exactly-event-object-do-in-angular-2 – Jameel Moideen Aug 30 '18 at 14:50

2 Answers2

1

Rebuid a similar object:

onActionChange({target: {value: '7'}});

Or split your code with something similar:

onActionChange($event) {
  setAction(parseInt($event.target.value));
}

setAction(value) {
  const selectedAction = value;
}

Then you're free to call

setAction(7)
Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50
0

To call it manually with onActionChange(7)

onActionChange($event) {
  const selectedAction = $event.target ? parseInt($event.target.value) : $event
  console.log('selectedAction', selectedAction)
}

This assumes that the value passed when you manually call it is numeric.

danday74
  • 52,471
  • 49
  • 232
  • 283