@input and @output decorator change event

After going through some decorator code @input\@output

I found different behavior.

In the code below, the component counter

gets its value from the parent component app

through the decorator @input

and emits changes through the decorator @output

.

My question is:

  • Why change the event when I was manually typing a value into the textbox.? When I was this.change.emit(this.count);

    only defining internally Increment\Decrement

    .

  • When I make changes using the button Increment\Decrement

    , I get the correct changed value in the component app

    (parent) , but when I manually enter the value, then I get [object Event]

    not typed. Why is that?

Plunker code below here.

Component

:

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'counter',
  template: `
    <div class="counter">
      <button (click)="decrement()">
        Decrement
      </button>
        <input type="text" [(ngModel)]="count">
      <button (click)="increment()">
        Increment
      </button>
    </div>
  `
export class CounterComponent {  
  @Input()
  count: number = 0;

  @Output()
  change: EventEmitter<number> = new EventEmitter<number>();

  increment() {
    this.count++;
    this.change.emit(this.count);
  }

  decrement() {
    this.count--;
    this.change.emit(this.count);
  }  
}

      

application component:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div class="app">
      <counter
        [count]="myCount"
        (change)="countChange($event)">
      </counter>
    </div>
  `
})
export class AppComponent {
  myCount: number = 10;
  countChange(event) {
    console.log(event); //log Event object below
    console.log('change called...!!!');
    this.myCount = event; 
  }
}

      

I tried changing the input type to , also changed the binding to 1st path: but doesn't seem to work. number

[ngModel]="count"

console.log (event);

Event {isTrusted: true, type: "change", target: input.ng-untouched.ng-valid.ng-dirty, currentTarget: counter, eventPhase: 3 ...}

+3


source to share


1 answer


The main idea of โ€‹โ€‹angular when working with events is the ability to use any standard DOM event in addition to the event @Output

.

So when you write

(change)="handler($event)"

      

angular will call handler

for both cases:



  • when you have @Output() change

    and is calledchange.emit()

  • when the standard event change

    triggered the input element

So, replace your event @Output

with something other than change

, and then it should work as you expect.

Fixed Plunker

+6


source







All Articles