Roy
Roy

Reputation: 910

How to call a function($event) manually in Angular 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

Upvotes: 2

Views: 925

Answers (2)

danday74
danday74

Reputation: 57215

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.

Upvotes: 0

Alexandre Annic
Alexandre Annic

Reputation: 10768

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)

Upvotes: 1

Related Questions