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--;
}
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);
}
In the chicld.component.html, you can paste the below code:
<h2>{{ myNewNumber }}</h2>
<h2>{{ myName.name }}</h2>
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>
Top comments (0)