Search code examples
angulartypescripteventemitter

Type 'number' is not assignable to type 'EventEmitter<number>'


I get this error when I try and assign value to be an EventEmitter of type number. Here is my code:

export class SpeedLimitComponent {
  @Output() public value = new EventEmitter<number>();

onInput(event: Event) {

this.value = +(\<HTMLInputElement\>event.target).value.split(',').join('');
console.log(this.value);
}

Error is above at this.value and below at value

<input
    type="text"
    placeholder="..."
    class="form-control"
    style="text-align: right"
    [value]="value | number: '.0':'en-US'"
    (input)="onInput($event)"
  />

I've tried

...value: EventEmitter<number> = new EventEmitter<number>();

thinking that the instance I created needs to be the same as the EventEmitter. What am I missing here?


Solution

  • You are using EventEmitter incorrectly.

    I don't know what is the use case, but you probably want to do this:

    const num = +event.target.value; this.value.emit(num);
    

    Event emitter is supposed to emit the value and not to assign value to it, and good practice is also to assign it to be readonly.

    Note that the + in code snippet is needed for casting from string to number.