简体   繁体   中英

Call method of another component file angular 2

I have two component files: file1.component.ts and file2.component.ts . On a button event, I want to call a method from file2.component.ts (for example ngOnInit() ) in file1.component.ts. 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.

Do not use life cycle methods(like ngOnInit..). Write a custom method, if you want use one method in another class you have two options.

  1. use Viewchild() In first component create object to access any method.

Example:

class FirstComponent {

@ViewChild(SecondComponent)
private sec: SecondComponent;

sec.methodName();

}
  1. Very simple this just extend the first component in second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM