【问题标题】:AngularJs : How to call child component method from parent componentsAngularJs:如何从父组件调用子组件方法
【发布时间】:2018-06-08 07:51:03
【问题描述】:

我正在将 AngularJS 应用程序迁移到 Angular 4。目前正在准备迁移到基于组件的架构。

我的问题是如何从父组件调用子组件方法。

我知道在 Angular 4 中我们可以使用 @ViewChild 来访问子方法。是否有 angularjs 1.6 的等效项或任何其他有助于更顺畅迁移的方法。

【问题讨论】:

标签: angularjs


【解决方案1】:

在 angularJS 中,我们使用$broadcast 事件与父控制器与子控制器进行通信。但这是一个$scope 方法。由于 angular 2 降低了范围,因此您不能使用此事件。

问题中已经提到了最佳解决方案。与广播相比,ViewChild 允许用户进行更多控制。所以我的建议是使用ViewChild

【讨论】:

    【解决方案2】:

    由于 Angular2+ 事件流是使用 RxJS 可观察对象传递给组件的,为了使迁移到 Angular 2+ 更顺畅,在 AngularJS 中也使用 RxJS 可观察对象。

    添加rxJS to AngularJS组件:

    <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();
            };
        };
    });
    

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 2020-06-27
      • 2016-12-08
      • 2020-06-15
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      相关资源
      最近更新 更多