Rendering AngularJS code inside React component

149 Views Asked by At

Is it possible to render AngularJS component inside React component which is rendered from an AngularJS component. I have a specific scenario where:

<angularjs-component-1>
    <react-component>
        <angularjs-component-2>
        </angularjs-component-2>
    </react-component>
</angularjs-component-1>

Inside of AngularJS app I have access to a library of react components which are in separate repo where they are exported and assigned to a window object so that they can be consumed inside of AngularJS app.

Inside of the angularjs-component-1 I have an access to a ref of react-component where I have to inject my angularjs-component-2.

I can append text to react-component from angularjs-component-1, but not sure how to inject another angularjs component/directive inside of it.

I don't have much experience with AngularJS and I am not sure if I am able to access angularjs-component-2 from angularjs-component-1 in order to pass it to the react component.

I don't think I can use angular2react since my react components are in separate repo, exported and assigned to window object so that they can be consumed in angularjs.

UPDATE: Solution found

<angularjs-component-1> has method which is passed to <react-component> that method is called from react and it passes ref to a div in which <angularjs-component-2> will be placed. Logic inside of that method is something like this:

function sendRef(ref) {
  var $angularComponent2 = angular.element('<angularjs- 
  component-2 ng-model="propName"></angularjs-component-2>');
  var reactComponent = angular.element(ref.current);
  reactComponent.append($angularComponent2);

  reactComponent.injector().invoke(function($compile) {
    var scope = angular.element($angularComponent2).scope();
    // if you need to assign some values to angular-component-2 scope 
    // this is the place to do it
    scope.propName = $scope.someValue;
    $compile($angularComponent2)(scope);
  });
}

Hope this helps someone.

0

There are 0 best solutions below