[英]Call method of another component file angular 2
I have two component files: file1.component.ts
and file2.component.ts
. 我有两个组件文件:
file1.component.ts
和file2.component.ts
。 On a button event, I want to call a method from file2.component.ts (for example ngOnInit()
) in file1.component.ts. 在发生按钮事件时,我想从file1.component.ts中的file2.component.ts(例如
ngOnInit()
)中调用一个方法。 Here is my code: 这是我的代码:
<!DOCTYPE html> <html> <head> <title>angular2 playground</title> <link rel="stylesheet" href="style.css" /> <script src="https://code.angularjs.org/2.0.0-beta.13/angular2-polyfills.js"></script> <script src="https://code.angularjs.org/tools/system.js"></script> <script src="https://code.angularjs.org/tools/typescript.js"></script> <script src="config.js"></script> <script src="https://code.angularjs.org/2.0.0-beta.13/Rx.js"></script> <script src="https://code.angularjs.org/2.0.0-beta.13/angular2.dev.js"></script> <script src="https://code.angularjs.org/2.0.0-beta.13/router.dev.js"></script> <script src="https://code.angularjs.org/2.0.0-beta.13/http.min.js"></script> <script> System.import('app') .catch(console.error.bind(console)); </script> </head> <body> <my-app> loading... </my-app> </body> </html>
I want to call ngOnInit()
method from the app.component.ts
, in the content-list.component.ts. 我想从content-list.component.ts中的
app.component.ts
调用ngOnInit()
方法。
Do not use life cycle methods(like ngOnInit..). 不要使用生命周期方法(例如ngOnInit ..)。 Write a custom method, if you want use one method in another class you have two options.
编写一个自定义方法,如果要在另一个类中使用一个方法,则有两个选择。
Viewchild()
In first component create object to access any method. Viewchild()
创建对象以访问任何方法。 Example: 例:
class FirstComponent {
@ViewChild(SecondComponent)
private sec: SecondComponent;
sec.methodName();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.