Showing posts with label angular2react. Show all posts
Showing posts with label angular2react. Show all posts
angular2react

angular2react

May 18, 2017


One line of code to turn any Angular 1 Component into a React Component

Installation


 npm install angular2react --save  


Usage



  1. Save a reference to the $injector

     let $injector  
     angular  
      .module('myModule')  
      .run(['$injector', function(_$injector) { $injector = _$injector }])  
    
  2. Create an Angular component

     const MyComponent = {  
      bindings: {  
       fooBar: '<',  
       baz: '<'  
      },  
      template: `  
       <p>FooBar: {this.$ctrl.fooBar}</p>  
       <p>Baz: {this.$ctrl.baz}</p>  
      `  
     }  
    
  3. Expose it to Angular

     angular  
      .module('myModule', [])  
      .component('myComponent', MyComponent)  
    
  4. Convert it to a React Component

     import { angular2react } from 'angular2react'  
     const MyComponent = angular2react('myComponent', MyComponent, $injector)  
    
  5. Use it in your React code

     <MyComponent fooBar={3} baz='baz' />  
    


Why step 1?


We need a reference to the $injector created by the Angular module that registered the Angular component you're exposing. That way we can manually compile your component.
If you use ngimport, you can skip step 1 and omit the last argument in step 4:
 import { angular2react } from 'angular2react'  
 const MyComponent = angular2react('myComponent', MyComponent)  


Caveats


  • Only one way bindings (<) are supported, because this is the only type of binding that React supports
  • Be sure to bootstrap your Angular app before rendering its React counterpart


Tests


 npm test  


License


Apache2

Note: Special thanks to Opensource@Coatue

Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developer.