AngularJs : How to call child component method from parent components

angularjs

1677 观看

2回复

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


1

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 发布者: 2017 年 12 月 27 日

1

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="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

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

    $scope.onEvent = function(message) {         
        $scope.subject.onNext(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) {
                console.log(message);
                $ctrl.message = message;
            });
        };
    }; 

    this.$onDestroy = function() {
        if (subscription) {
            subscription.dispose();
        };
    };
});
作者: georgeawg 发布者: 2017 年 12 月 27 日
32x32