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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With