AngularJs : How to call child component method from parent components


1677 观看


12 作者的声誉

I am doing Migration of AngularJS application to Angular 4.Currently preparing for migration that is conversion to Component based architechture.

My question is how can I call child component method from parent component.

I know in Angular 4 we can use @ViewChild to access the child method. Is there any equivalent for angularjs 1.6 or any other approach that can help in smoother migration.

作者: kashif khan 的来源 发布者: 2017 年 12 月 27 日

回应 (2)


22339 作者的声誉

In angularJS we use $broadcast event to communicate with parent controller to child controller. But this is a $scope method. Since angular 2 drops the scope, you cannot use this event.

The best solution is already mentioned in the question. ViewChild allows much more control to the user compare to the broadcasts. So my recommendation is to go with ViewChild

作者: Sachila Ranawaka 发布者: 27.12.2017 05:51


39398 作者的声誉

Since Angular2+ event streams are passed to components using RxJS observable objects, to make the migration to Angular 2+ smoother, use RxJS observables in AngularJS as well.

To add rxJS to AngularJS components:

<script src="//"></script>
<script src="//"></script>
<script src="//"></script>
var app = angular.module('myApp', ['rx']);

app.controller("parentCtrl", function($scope, rx) {
    $scope.subject = new rx.Subject(); 

    $scope.onEvent = function(message) {         

app.component("childComponent", {
    controller: "childCtrl",
    bindings: { subject: "<" },
    template: `<div>{{$ctrl.message}}</div>`

app.controller("childCtrl", function(rx) {
    var subscription;
    this.$onChanges = function(changes) {
        if (changes.subject} {
            subscription = subject.subscribe(function onNext(message) {
                $ctrl.message = message;

    this.$onDestroy = function() {
        if (subscription) {
作者: georgeawg 发布者: 27.12.2017 08:23