我们正在尝试将数组数据从Parent组件传递给Child,并且抛出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()
答案 0 :(得分:1)
请重新检查您的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()
参数传递数据。
答案 1 :(得分:0)
您无需在子级上将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;
答案 2 :(得分:0)
据我所知,您不需要Input()装饰器,并且如果删除它,它应该可以工作。如前所述,前提条件是TSFComponent实际上是在RFComponent模板内使用的。
答案 3 :(得分:0)
您使用@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;
}