簡體   English   中英

角度2的另一個組件文件的調用方法

[英]Call method of another component file angular 2

我有兩個組件文件: file1.component.tsfile2.component.ts 在發生按鈕事件時,我想從file1.component.ts中的file2.component.ts(例如ngOnInit() )中調用一個方法。 這是我的代碼:

 <!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> 

我想從content-list.component.ts中的app.component.ts調用ngOnInit()方法。

不要使用生命周期方法(例如ngOnInit ..)。 編寫一個自定義方法,如果要在另一個類中使用一個方法,則有兩個選擇。

  1. 在第一個組件中使用Viewchild()創建對象以訪問任何方法。

例:

class FirstComponent {

@ViewChild(SecondComponent)
private sec: SecondComponent;

sec.methodName();

}
  1. 很簡單,這只是將第二個組件擴展到第二個組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM