0

In angular there is a method called ngOnChanges. i am trying to understand that,I tried with this code. but i am not getting any output.

any one help me to understand?

here is my code :

import { Component, OnInit, Input, OnChanges } from '@angular/core';
import { StorageService } from '../shared/service/storage.service';


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

    link = {};

    constructor(private storage:StorageService) {
        setTimeout(()=> {
            this.link = "ariffff";
        }, 1000 );
        // console.log( this.storage.name);
    }

    ngOnInit() {}

    ngOnChanges(changes) {
      console.log(this.link, changes); //getting nothing
    }

}
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247
  • 1
    You don't have any inputs to that component, what were you expecting to trigger the method? I'd recommend reading the descriptions in https://angular.io/guide/lifecycle-hooks. – jonrsharpe Apr 26 '18 at 12:18
  • Agreed with @jonrsharpe, you can't say something doesn't work when you don't know how it works. Similarly, you can't try to understand something based solely on its name. Read the documentation, it's there for a reason. –  Apr 26 '18 at 12:31
  • I have a object in service file. which is updated by some of component. when the object change how can observe? so i will take some decision to other component – 3gwebtrain Apr 26 '18 at 13:08
  • https://stackoverflow.com/a/49388249/5695162) – Vikas Apr 26 '18 at 13:38

2 Answers2

2

How To Use:

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
 @Input()
 prop: number;

 ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
 }
}

Description

ngOnChanges is called right after the data-bound properties have been checked and before view and content children are checked if at least one of them has changed. The changes parameter contains the changed properties.

From https://angular.io/api/core/OnChanges

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Gauravbhai Daxini
  • 2,032
  • 2
  • 22
  • 28
0

Per https://angular.io/api/core/OnChanges:

Lifecycle hook that is called when any data-bound property of a directive changes.

For further clarification: Components are a subset of Directives (https://angular.io/api/core/Component). So for example if you have a child component whose input prop changes the function is called. Since your Component doesn't have a data-bound property which is changing, your ngOnChanges() won't be called.

By the way, it is good practice to implement the OnChanges interface:

class MyComponent implements OnChanges
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Daddelbob
  • 406
  • 4
  • 13