1

My HTML looks something like this:

<input type="number" class="form-control" id="khatianNumber" required [(ngModel)]="big.khatianNumberP1" name="khatianNumber" #khatianNumber="ngModel">

<p id="parapart" align="center">/</p>

<input type="number" class="form-control" id="khatianNumber2" required [(ngModel)]="big.khatianNumberP2" name="khatianNumber2" #khatianNumber1="ngModel">

And my Angular looks something like this,

export class RegistrationComponent implements OnInit,OnChanges {
isRequesting = false;
steps = [];
model = {
  khatianNumber: '',
};

big = {
  khatianNumberP1: '',
  khatianNumberP2: '',
}
ngOnChanges(changes: SimpleChanges){
    if (changes['big.plotNumberP1']){
        alert("hi");
    }
}
}

I've never used angular like this, I usually had to use scopes and controllers.

Can someone tell me what am I doing wrong? Is there something wrong with my HTML or am I using the models wrong? I am new to Angular and would greatly appreciate if someone could clear this doubt!

coder123
  • 841
  • 1
  • 7
  • 19

3 Answers3

0

Hi can you try like that,

if thet below one is not working means try change your form template driven to model driven forms(Reactive forms)

The below one i have used Reactive forms its works for me

ngOnChanges(changes: {[propKey: string]: SimpleChange})
    {
        if(changes.hasOwnProperty('big.khatianNumberP1')){}
}
Robert
  • 3,373
  • 1
  • 18
  • 34
0

ngOnChanges is used for data passed from parent to child components. For catching model changes you need to use an event listener which is ngModelChange or you can basically use the change listener if you have a basic form. See this post for details about the difference between them, and how to use both: (change) vs (ngModelChange) in angular

Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43
0

If you want to run an action when there is a change in a form element, it is best to separate [(ngModel)]="big.khatianNumberP1" into [ngModel]="big.khatianNumberP1" and (ngModelChange)="numberP1Changed()".

Then, in your component code, you can have a handler which does whatever you need:

export class RegistrationComponent {
    isRequesting = false;
    steps = [];
    model = {
        khatianNumber: '',
    };
    big = {
        khatianNumberP1: '',
        khatianNumberP2: '',
    }

    numberP1Changed() {
       alert("hi - new value - " + this.big.khatianNumberP1);
    }
}
Mark Hughes
  • 7,264
  • 1
  • 33
  • 37