Alex Cooper
Alex Cooper

Reputation: 597

Angular: Is there a way to detect changes made on an object property when bound to a child component

In a simple app with parent and child components (app and hello) an object defined in the parent can be bound to the child in multiple ways.

Even with simple property binding, changes made to the object properties in the child component are detected and reflected to the parent, but how do we tap into the change event to do something else?

This StackBlitz shows

  1. one-way property binding
  2. two-way banana-in-a-box binding
  3. split property and event binding

In each case, changes made to the properties of the person object in the child component (firstName and lastName) are detected and reflected back to the parent app component.

However none of the binding strategies allow for changes on the properties to be detected.

The only way to get the changes value to increment in the parent, is to click the emit button in the 3rd instance where I explicitly call

this.memberChange.emit(this.member);

This is picked up by the event binding

(memberChange)="memberChange()"

Only in this case does changes get incremented in the parent app component.

So is it possible to detect property changes automatically without explicitly emitting a change event?

Upvotes: 1

Views: 2635

Answers (1)

SparrowVic
SparrowVic

Reputation: 279

of course it is possible. You don't need to use a button each time to emit a value. You can take advantage of the many different events that are offered by HTML Elements. For example, if you want it to emit every time the value changes in the input field, you can use event (input) - do not confuse with (change) because it works similarly, but it will emit only when the value is commiited, e.g. you click outside the input field.

For example, the code below:

export class ChildComponent{
  @Output() onChange = new EventEmitter();

  onInputChange(value):void {
    this.onChange.emit(value);
  }
}

<!-- Child component HTML -->
<input (input)="onInputChange($event)">

export class ParentComponent {
  counter = 0;

  counterFunc(value) {
    this.counter++;
    console.log(this.counter);
  }
}

<!-- Parent component HTML -->
<child-component
  (onChange)="counterFunc($event)"
>
</child-component>

Upvotes: 0

Related Questions