Maddy
Maddy

Reputation: 2224

Detecting changes to a model within the same component - Angular

I know that we can use @Input with onChange hook to detect changes done in the parent component within the child component. But my use case is to detect changes done to the model within the same component. component.ts:

export class MyComponent implements OnInit {

    private myExmapleModel: MyModel;

    ngOnInit: void {
           this.momyExmapleModeldel = new MyModel('', '', '');
    }

}

I two-way bind this myExampleModel to the template html and want trigger a function when a value in MyModel instance changes, within the same MyComponent. How can I do that?

Upvotes: 2

Views: 5400

Answers (2)

WasiF
WasiF

Reputation: 28859

if you want to detect change on input, use input-event or want to detect change on focus-away i.e. cursor not in input box, use change-event

<input [(ngModel)]="name" (input)="changed()" />

<input [(ngModel)]="name" (change)="changed()" />

changed() {
  console.log('name changed')
}

Upvotes: 0

Max Koretskyi
Max Koretskyi

Reputation: 105497

If you're using your myExmapleModel in html like this:

<input ([ngModel])="myExmapleModel">

You can use ngModelChange callback like this:

<input [ngModel]="myExmapleModel" (ngModelChange)="onChange($event)"

Upvotes: 3

Related Questions