Angular @Input binding using function calling multiple times

别来无恙 提交于 2020-03-05 03:04:21

问题


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.


回答1:


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();
  }
}



回答2:


Go stateless with async pipes. I think this is closer to what you want to do anyway. I use async pipes wherever possible because its cleaner than using properties for everything -- less unintended consequences too.

@Component({
  selector: 'app-parent',
  template: '<app-child [info]="info$ | async"></app-child>',
})
export class ParentComponent implements OnInit {
  info$ = this.service.getData().pipe(
    map(data => JSON.parse(data))
  );

  constructor(private service: MyService) { }
}


来源:https://stackoverflow.com/questions/59686730/angular-input-binding-using-function-calling-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!