I am trying to make something work on angular2 and I am unable to find something about this behavior.
I have an application that implements a custom component like this
This is explained in the Template Syntax doc, in the Two-Way Binding with NgModel section:
Internally, Angular maps the term,
ngModel
, to anngModel
input property and anngModelChange
output property. That’s a specific example of a more general pattern in which it matches[(x)]
to anx
input property for Property Binding and anxChange
output property for Event Binding.We can write our own two-way binding directive/component that follows this pattern if we're ever in the mood to do so.
Note also that [(x)]
is just syntactic sugar for a property binding and an event binding:
[x]="someParentProperty" (xChange)="someParentProperty=$event"
In your case, you want
so your component must have an inputText
input property and an inputTextChange
output property (which is an EventEmitter
).
export class MyComp {
@Input() inputText: string;
@Output() inputTextChange: EventEmitter = new EventEmitter();
}
To notify the parent of changes, whenever your component changes the value of inputText
, emit an event:
inputTextChange.emit(newValue);
In your scenario, the MyComp component binds input property inputText
using the [(x)]
format to ngModel, so you used event binding (ngModelChange)
to be notified of changes, and in that event handler you notified the parent component of the change.
In other scenarios where ngModel isn't used, the important thing is to emit()
an event whenever the value of property inputText
changes in the MyComp component.