[英]Unable to pass data between components
我们正在尝试将数组数据从父组件传递给子组件,并抛出TypeError: Cannot read property 'setData' of undefined
>下面是我们正在尝试的
父组件
export class RFComponent implements DoCheck {
finalResult: SModel[];
@ViewChild(TSFComponent, {static: false})
private childVar: TSFComponent;
........
click() {
this.elem = this.getResult(this.prj);
this.childVar.setData(this.finalResult);
}
子组件
export class TSFComponent implements DoCheck {
@Input() setData(e: SModel[]) {
this.tjlData = e;
}
我不确定为什么会收到Cannot read property
错误,因此从父级调用setData()
请重新检查您的RFComponent
。 在那里,您会看到this.finalResult
没有在任何地方定义。 您需要将其定义为成员变量,例如
private finalResult: string = 'something'
那么您就可以将其传递给其他组件。
但这也不是最佳做法。 据我所知,您没有正确定义组件。 即使您可以在Angular中使用纯类,但通常组件在类声明中都有装饰器,您可以在其中定义选择器,templateUrl和样式,例如
@Component({
selector: 'some-selector',
templateUrl: 'my-template.component.html',
styleUrls: ['my-style.component.scss']
})
在那里,您可以在模板中引用其他类,然后通过@Input()
, @Output()
参数传递数据。
您无需在子级上将setData()定义为Input()。 使用viewchild时,您正在创建对子组件的引用,因此可以访问其上的方法。 您没有将setData方法从父级传递给子级。
export class TSFComponent implements DoCheck {
setData(e: SModel[]) {
this.tjlData = e;
}
您还需要在view child中引用dom元素。
<child #TSFComponent></child>
@ViewChild('TSFComponent', {static: false}) childVar: TSFComponent;
据我所知,您不需要Input()装饰器,并且如果删除它,它应该可以工作。 如前所述,前提条件是TSFComponent实际上是在RFComponent模板内使用的。
您使用@ViewChild错误。 您基本上不需要使用setData()函数来“设置”数据。 如果在子组件中使用@Input()装饰器,则可以设置并在其中声明变量,并使用从父组件传递来的数据。
您可以这样做:
父组件HTML:
<child-component [parentData]="data"></child-component>
子组件.ts
@Input data: any;
然后,如果要设置与子组件变量/对象相等的变量或对象,则在父组件中引用子组件变量并分配值。 见下文:
给数据对象赋予新值的子组件
someCode() {
data = {
someData: "Hi there",
someMoreData: "Hello there again"
}
父组件引用和关联新对象
parentData: any;
assignData {
this.childComponent.data = parentData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.