Reputation: 2343
I know we use
()
for detecting event like
<div (click)="doSomething()">
or
<div (blur)="doSomethingElse()">
and {{}}
for converting variable to string in template like
<div>{{a_variable_i_want_to_show}}</div>
but what do we use [()]
for besides two way binding in ng-model?
Is there a generic usage?
Upvotes: 0
Views: 173
Reputation: 364707
When used with NgModel, [()]
sets up two-way databinding between a component property and a DOM form element. Any change we make to the component property is automatically propagated to the DOM, and any change we make to the form element (i.e., the DOM) is automatically propagated to the component property.
When used with a component, [()]
sets up two-way databinding between a parent component property and a child component property. Any change we make to the parent component property is automatically propagated to the DOM. However, any change we make to the child component property is not automatically propagated to the parent – we must use emit()
. So it's a little different than NgModel.
The child component must define an input property and an output property, which is an EventEmitter. If the input property is named x
, the output property must be named xChange
. The child component must explicitly emit any change to x
by calling xChange.emit(newValue)
.
The reason for the naming requirements is because [(childProp)]="parentProp"
is a shorthand for [childProp]="parentProp" (childPropChange)="parentProp=$event"
.
If you need to execute some logic in the parent when a new value is emitted from the child, you'll want to use the expanded form: [childProp]="parentProp" (childPropChange)="doSomething($event)"
.
Upvotes: 0
Reputation: 2813
It is two-way binding. Checkout their cheatsheet:
Sets up two-way data binding. Equivalent to:
<my-cmp [title]="name" (titleChange)="name=$event">
Upvotes: 3