Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use angular 6 component in react application

how to use angular 6 component in react application.

I have created an angular component and created a distributed package which i can use it another angular project, how can i use same component in react js apps.

Thanks, Srinivas

like image 252
Srinivas Ganaparthi Avatar asked Mar 05 '23 10:03

Srinivas Ganaparthi


1 Answers

Import a Angular 6 module in React

Step 1: Configure AppModule for exporting as a web component from LoginComponent

@NgModule({
  declarations: [
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [],
  entryComponents:[
    LoginComponent
  ]
})
export class AppModule { 
  constructor(private injector:Injector){

  }

  ngDoBootstrap() {
    const el = createCustomElement(LoginComponent, { injector: this.injector });
    customElements.define('ng-login', el);
   }
}

Step 2: Configure the component

@Component({
  selector: 'ng-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  encapsulation: ViewEncapsulation.Native
})
export class LoginComponent {
  @Input() username = '';
  @Input() password = '';

  @Output('login') login = new EventEmitter<any>();

  constructor() { }

  doLogin() {
    let user = {
      "username": this.username,
      "password": this.password
    };
    this.login.emit(user)
    console.log('emitting event');
  }
}

Step 3: Export as web component

ng build --prod --output-hashing none

Step 3: Copy below three files from dist/ng-login folder and paste inside ng-elements folder

runtime.js
polyfills.js
main.js"

Step 4: Open index.html and add the three files

 <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>

    <div id="root"></div>

    <script type="text/javascript" src="./ng-elements/runtime.js"></script>
    <script type="text/javascript" src="./ng-elements/polyfills.js"></script>
    <script type="text/javascript" src="./ng-elements/main.js"></script>
    
  </body>

Step 5: define parameters to pass to the component in react

constructor(props){
    super(props)
    this.state = {username:'default-username', password:'default-password'}
  }

Step 6: Add element

<ng-login ref={elem => this.nv = elem} username={this.state.username} password={this.state.password}></ng-login>

Step 7: subscribe to events

componentDidMount() {
    this.nv.addEventListener("login", this.handleNvEnter);
  }

  componentWillUnmount() {
    this.nv.removeEventListener("login", this.handleNvEnter);
  }

Step 8: Display results

<div>
  User Name: {this.state.username}
</div>
<div>
  password: {this.state.password}
</div>

Ref: https://medium.com/@balramchavan/integrate-import-angular-v6-component-s-inside-react-js-applications-da5cc03107b4

like image 154
Mosè Raguzzini Avatar answered Mar 11 '23 21:03

Mosè Raguzzini