DEV Community

Phinehas Alabi
Phinehas Alabi

Posted on • Edited on

Difference between ngOnChanges vs ngOnInit in angular component

In simplest terms:
ngOnChange - changes on every click event made or component interaction

ngOnInit -Initializes only once upon server start
example below:
in component.ts file:
ex. app.component.ts

 private number: number = 234;
  name: string = 'Oyata';
  user = {
    name: 'Yamata',
  };

get counter() {
    return this.number;
  }
  set counter(value) {
    this.number = value;
  }
  increment() {
    this.counter++;
  }
  decrement() {
    this.counter--;
  }
Enter fullscreen mode Exit fullscreen mode

Paste below code in any child component.ts file.
Based on the exmaple below I name the file child.component.ts

ngOnChanges(changes: SimpleChanges) {
    // runs before ngOnInit()
    // executes on every change
    const newNumberChange: SimpleChange = changes.myNewNumber;
    console.log(
      'Previous Value - (ng on changes): ',
      newNumberChange.previousValue
    );
    console.log(
      'Current Value - (ng on changes): ',
      newNumberChange.currentValue
    );
    this.myNewNumber = newNumberChange.currentValue;
  }
 ngOnInit() {
    // executes only one time
    // use to initialize or call functions / methods
    console.log('ngOnInit Value: ', this.myNewNumber);
  }
Enter fullscreen mode Exit fullscreen mode

In the chicld.component.html, you can paste the below code:

<h2>{{ myNewNumber }}</h2>
<h2>{{ myName.name }}</h2>
Enter fullscreen mode Exit fullscreen mode

In app.component.html, you can paste the below code:

<button (click)="decrement()">Subtract</button>
<div>
  <app-child [myNewNumber]="counter" [myName]="user"></app-child>
</div>
<button (click)="increment()">Add</button>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)