Make component detect change in Input

Viewed 120

The situation is:
I have an angular form:

<form #f="ngForm" (ngSubmit) = search(f) novalidate >
  <input name="inputCustomerId" [(ngModel)]="customerId" type= "number">
  <a type="button" (click)="search(f)">Search</a>
</form>
<app-graph *ngIF="customerId" [nodeName]="customerId"></app-graph>

And in the .ts file:

export class C implements OnInit{
  customerId: any; 
  constructor(){}
  ngOnInit(){}
}
search(form:ngForm){
  if(form.valid){
    this.customerId = form.value.inputCustomerId;
  }
}

The Problem is when clicking the button the app-graph component doesn't detect the input change.
How can I make it reload or update data?

2 Answers

Your structure is the following

Parent Component

  • --Child Component 1

  • --Child Component 2

Your customerId belongs to child Component 1. Angular will not transfer that state automaticaly to child component 2.

It will initialy load both components with the initial state but changes will not be transfered across components.

In that case you need to make an Output with EventEmitter from Child Component 1. And your child Component 2 will have to listen for those changes.

If you need more help to implement those changes, update your answer with all components

The solution was to implement ngOnChanges() method in the child component "app-graph".
So the code is:

export class GraphComponent implements OnInit, OnChanges {
  @Input()
  private nodeName : any; 
 
  constructor(){}
  ngOnInit(){}

  ngOnChanges(changes:SimpleChanges): void {
    console.log("Previous nodeName: ",changes.nodeName.previousValue);
    this.myLogic(changes.nodeName.currentValue);
  }
  
  myLogic(nodeName: any){
    console.log(nodeName);
  }
  
}
Related