Dave Nottage
Dave Nottage

Reputation: 3602

Detecting a change in model data within a component

I imagine I may be missing something really obvious, however this is my situation - I have some data that is being assigned to the ngModel input of a component, e.g:

Typescript:

SomeData = {
  SomeValue: 'bar'
}

Fragment of view template:

<foo [(ngModel)]="SomeData.SomeValue"></foo>

Component:

import { Component, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'foo',
  template: `<input type="text" [ngModel]="value" (ngModelChange)="modelChange($event) 
(change)="elementChange($event)"/>`
})
export class FooComponent {

  ngOnChanges(changes: SimpleChanges) {
    // Fired when @Input members change
  }

  modelChange(value) {
    // Fired when a change in the HTML element will change the model, *not* when the model changes from elsewhere 
  }

  elementChange(event) {
    // Fired when the HTML element value changes
  }
}

As per my comments in the example, I'm able to tell when Inputs change, when the value of the HTML element will change the model, and when the value of the HTML element changes.

I want to be able to know from within the component, when the property that is assigned to ngModel in the view template (i.e. SomeData.SomeValue) changes. I know that Angular does this itself, because it updates the value in the HTML, however I'm at a loss as to how to intercept this change as well, from within the component, so some other action may be taken.

Upvotes: 1

Views: 1354

Answers (1)

shusson
shusson

Reputation: 5782

SomeData.SomeValue is not controlled by angular, all you do is tell angular to bind to a property and bind to an event. Angular will then run it's own change detection mechanism which will update the view. If you are interested in how Angular does this take a look at this blog.

If you want to be notified of changes to SomeData.SomeValue you'll have to set up your own system, this can be as simple as a callback or a pub/sub. But it's really too broad to go into here.

Upvotes: 2

Related Questions