Search code examples
angularangular-changedetection

Angular @Input binding using function calling multiple times


I'm using Angular 8.

I have a child component with one @Input() property. This input has to be modified before binding and thus using method to return the data for binding like

<app-child [info]="getInfo()"></app-child>

And in the parent component, the getInfo() returns value like

getInfo(): any|null {
  console.log('called...');

  if (this.data) {
    return JSON.parse(this.data);
  }

  return null;
}

But this way, the method is called again and again whenever some event occurs in the child component.

Stackblitz example: https://stackblitz.com/edit/angular-child-com

Produce issue:

The form is rendered from the child component which accepts input from a method as described above.

Click on any button or input field and you can see the console log printing string from the method call with each event.

This is resulting in multiple times OnChange event trigger in the child components.


Solution

  • You should retrieve the data and store it in a property in the parent component that you then pass to data binding with the child component. Angular will take care of the change detection

    @Component({
      selector: 'app-parent',
      template: '<app-child [info]="info"></app-child>',
    })
    export class ParentComponent implements OnInit {
      info;
    
      constructor(private service: SomeDataService) {}
    
      ngOnInit() {
        this.info = this.service.getData();
      }
    }