Issue
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
- change text input
- click "cancel"
- 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>
Answered By - Anton Marinenko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.