Home > Software design >  ngOnChanges not firing at all on my component
ngOnChanges not firing at all on my component

Time:10-22

I am trying to test ngOnchanges so I've created a new project and here is my app.component.ts and .html

app.component.ts:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnChanges {

  @Input() mydata?: string;
  

  ngOnChanges(changes: SimpleChanges) {

    console.log(changes); // This does not appear in my console

  }

  change() {
    this.mydata = 'some change here';
  }

}

app.component.html

<h1>NG Changes</h1>

Changes: {{ mydata | json }}

<button (click)="change()">Change</button> 

Why I'm I not getting any result from ngOnchanges ... It seems like it's not being fired at all.

How can I fix this?

CodePudding user response:

ngOnChanges will only be triggered when reference to the @Input variables are adjusted by it's parent component. At the moment you do don't seem to have any parent-child component relationship.

Eg.

Child component (*.ts)

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

@Component({
  selector: 'app-child',
  template: `<h1>App child</h1>`
})
export class ChildComponent implements OnChanges {
  @Input() mydata?: string;

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
  }
}

Parent component (*.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  data: any;
}

Parent Template (*.html)

<app-child [mydata]="data"></app-child>

<hr>
<input #myInput />
<button (mouseup)="data=myInput.value">Push value to data</button>

Also note that the ngOnChanges would only be triggered if the values changes, so trying to click the button again with the same value in the above example wouldn't trigger it.

Working example: Stackblitz

  • Related