0
votes

The official Angular docs says:

"ngOnChanges is a lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes.

It is a little bit unclear to mean that if the updated/latest input property actually available in ngOnChanges lifecycle method. So I did a simple experiment as:

//trmplate.html
<p [mydirective] = "GetFirstStudent().Name"></p>

where Name is a property in the component, and I have set the first person's name to be "Michael".

so in the directive class that as mydirective selector:

@Directive({
    selector: "[mydirective]"
})
export class CustomDirective{
   ...
    @Input("mydirective")
    personName: string;

    ngOnChanges() {
       console.log(personName);
    }
}

so I refresh the browser, and the console does have the following output:

Michael

So this confirmed that in ngOnChanges, I can access the latest input properties.

Is my understanding correct?

3
Are you asking if ngOnChanges works? If so, the answer is yes. - Vlad Vidac
use ngOnChanges(changes : SimpleChanges) . changes.personName.currentValue will store the current value - CruelEngine
What exactly is your question? You basically answered the question you asked yourself by proving that the latest value is in fact Michael, so I'm not sure what you're looking for here. - Jesse

3 Answers

1
votes

You can found working example here StackBlitz Link

ngOnChanges(change: SimpleChanges){
  console.log(change['valueFromParent']);
  if (change['valueFromParent'].currentValue === undefined ){
    this.currentStatus = 'Not Change Detected';
  }
 else if(change['valueFromParent'].currentValue === true){
   this.currentStatus = change['valueFromParent'].currentValue
 }
 else if( change['valueFromParent'].currentValue === false) {
   this.currentStatus = change['valueFromParent'].currentValue
 }
}
0
votes

Like this:

ngOnChanges(changes: SimpleChanges) {
   console.log(changes.personName);
   if (changes.personName)
   console.log(changes.personName.currentValue)
}
0
votes

Your implementation works well for Strings and Integers because they are passed by value but not for Arrays and Objects inputs because they are passed by reference

SimpleChanges argument is used to get new and previous values of input properties

ngOnChanges(changes: SimpleChanges) {
 for (let propName in changes) {  
  let change = changes[propName];
  let curVal  = change.currentValue;
  let prevVal = change.previousValue;
  console.log(curVal);
  console.log(prevVal);
 }
}