使用多次调用函数的角度@Input绑定 [英] Angular @Input binding using function calling multiple times

查看:100
本文介绍了使用多次调用函数的角度@Input绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular 8

我有一个带有一个 @Input()属性。在绑定之前必须修改此输入,并因此使用方法返回要绑定的数据,例如

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>

在父组件中, getInfo()返回类似

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示例: https://stackblitz.com/edit/angular-child-com

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

产生问题:

从子组件呈现表单,该子组件接受上述方法的输入。

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.

这会导致子组件中的多次 OnChange 事件触发。

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

推荐答案

您应该检索数据并将其存储在父组件的属性中,然后将其传递给与子组件。 Angular将负责更改检测

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

这篇关于使用多次调用函数的角度@Input绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆