Question:
How Angular "change" output propagates input event implicitly?

Problem

I'm facing a strange behavior, I have a simple component that wrap a text input:


export class InplaceInputComponent {

  @Input() value: string;

  @Output() change = new EventEmitter<string>();


  editedValue: string;


  inputChange(event: any) {

    this.editedValue = (event.target as HTMLInputElement).value;

  }


  ok() {

    this.change.emit(this.editedValue);

  }


  cancel() {

    this.editedValue = this.value;

  }

}


Template:


<input

  type="text"

  [value]="value"

  (change)="inputChange($any($event))"

  [style]="'padding: 5px; border: 1px solid blue;'"

/>

<button type="button" (click)="ok()">OK</button>

<button type="button" (click)="cancel()">Cancel</button>


Parent component:


<inplace-input [value]="name" (change)="onNameChange($any($event))"></inplace-input>


If I modify input and click "cancel", the parent component receives the "change" event, even if the EventEmitter wasn't called. If I change the @Output from "change" to "textChange", this weird behaviour stops. Can you explain me why, and what are the "reserved words" for custom components events?


Steps to reproduce: >https://stackblitz.com/edit/angular-ivy-muspg2?

>file=src%2Fapp%2Fapp.component.ts


  1. change text input

  2. click "cancel"

  3. you can see the received event


Solution

You are facing a native HTML behaviour here. Actually, your HTMLInput element is located in an internal component and emits change events with ability to bubbling. So, to solve this simple problem you have to rename your Output from the change event to any other, or I would prefer to stop bubbling the change event explicitly.


Like this:


<input

  type="text"

  [value]="value"

  (change)="inputChange($any($event)); $event.stopPropagation()"

  [style]="'padding: 5px; border: 1px solid blue;'"

/>

<button type="button" (click)="ok()">OK</button>

<button type="button" (click)="cancel()">Cancel</button>



Ritu Singh

Ritu Singh

Submit
0 Answers