从子到父的角度传递数据

nik*_*ar4 7 event-listener typescript output childviews angular

我正在学习/研究Angular项目,我已经做了很多,我尝试以"正确的方式"做事,所以现在我想做的是:

我想从子组件到父组件获取变量(输出),但我不想使用输出,我不想听它,我想在父母需要的时候得到它,像child.getVariable()我这样的东西我发现一个帖子说我应该使用childview,但问题与我的不一样,所以我想知道使用childview从子组件获取数据是一个好习惯吗?

jez*_*zah 4

您是否只需要从父组件的模板中访问子组件的变量?如果是这样,您可以使用:

<child-component #childComponentRef></child-component>
Run Code Online (Sandbox Code Playgroud)

然后,您可以从父模板中访问#childComponentRef.someVariable。否则我认为 Angular 团队推荐共享服务。无论如何,它们的用途更加广泛。请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-and-children-communicate-via-a-service