问题
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