另一个组件文件的调用方法角度为2

时间:2017-02-20 16:12:48

标签: function angular components

我有两个组件文件: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中的ngOnInit()调用app.component.ts方法。

1 个答案:

答案 0 :(得分:1)

不要使用生命周期方法(如ngOnInit ..)。编写一个自定义方法,如果你想在另一个类中使用一个方法,你有两个选择。

  1. 使用Viewchild()在第一个组件中创建对象以访问任何方法。
  2. 示例:

    class FirstComponent {
    
    @ViewChild(SecondComponent)
    private sec: SecondComponent;
    
    sec.methodName();
    
    }
    
    1. 非常简单,这只是扩展第二个组件。