请教个编码问题 angular typescript

y
yanshuimangmang
楼主 (北美华人网)
export class ComponentB { functionToBeCalledInB(): void{ } } export class ComponentA implement OnInit { // how to reference componentB in a function of ComponentA? frameworkComponents:any={ componentB:ComponentB, } functionInAToCallB(){ // here, what should be the correct syntax? I am new to typescript // I have tried these ways, but no success this.frameworkComponents.componentB.functionToBeCalledInB(); this.frameworkComponents.ComponentB.functionToBeCalledInB(); } }
金银岛
这两个component有关系吗?如果A的template里有B的话,可以在A的ts文件里用ViewChild来找到template上的那个B,然后就能call B的method了。
y
yeah333
有从属关系用@output 或@viewchild。如果没有关系,加一个service , inject到两个component 里,通过event在A emit, 在B里Subscribe event, 调用B方法
y
yanshuimangmang
这两个component有关系吗?如果A的template里有B的话,可以在A的ts文件里用ViewChild来找到template上的那个B,然后就能call B的method了。
金银岛 发表于 2023-05-17 23:28

多谢,有从属关系的,A里面有B component.
y
yanshuimangmang
有从属关系用@output 或@viewchild。如果没有关系,加一个service , inject到两个component 里,通过event在A emit, 在B里Subscribe event, 调用B方法
yeah333 发表于 2023-05-18 00:31

export class ComponentA implement OnInit { // 多谢。请问这个frameworkComponents 是什么类型?是一个array还是一个anonymous class? frameworkComponents:any={ componentB:ComponentB, }
y
yeah333
用花括号的是object, 用中括号是array. 你的code 里的问题是没有实例化componentB,就使用它。如果你改成componentB : new ComponentB(), 应该work