How can I use Angular 2 in a .NET 4 Web Forms project? - asp.net

I have a ASP.NET 4 Web Forms project written in C#. I would like to add Angular 2. I've seen a lot of examples on the web using ASP.NET 5 but I can't figure out how to do it in my project.

Have faced similar requirement and did some POC on this and definitely moving forward with it . I worked on with each .aspx page as stand alone angular 2 SPA app. This means each aspx page will have its own App.Component.ts and main.ts file(file name based on Angular 2 documentation). main.ts file contains the code to bootstrap the application (sample code below) so there will be a main.ts file for each .aspx page.
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_BINDINGS} from 'angular2/http';
import {HomeComponent} from './home.component';
bootstrap(HomeComponent, [HTTP_BINDINGS])
.catch(err => console.error(err));
There will be one app.component.ts(named it home.component.ts for my home.aspx) file for each aspx page.
Now in the config file which contains Sytem.config details i defined new map and package entry for my home.aspx as shown below:
System.config({
transpiler: 'typescript',
typescriptOptions: {
emitDecoratorMetadata: true,
experimentalDecorators: true
},
map: {
app: '../../Javascript/angular/app',
home: '../../Javascript/angular/home'
},
packages: {
app: { main: './main.ts', defaultExtension: 'ts'},
home: { defaultExtension: 'ts' }
}
});
And finally I moved the System.import code part to .aspx page(code below). Each page will import its own package defined in sytem.config.
<script>
System
.import('home/main-home')
.catch(console.error.bind(console));
</script>
here i have named my main.ts as main-home.ts.
Hopefully this helps you and others. Also i am open for suggestion and review/alternate solution of this approach.
For reference please see: bootstrapping-multiple-angular-2-applications-on-the-same-page

I totally agree with #pawan's answer but yes #pawan i found a nice solution of this. This solution definitely helped me and hope it will help all of you too.
We don't need to create main.ts and AppComponent.ts for each and every page.
We need to make our main component which we are bootstrapping dynamic. In our case, in app.component.ts, i am bootstrapping our component dynamically based on url of current page.
Let's say if your page is home.aspx then boostrap HomeComponent or about.aspx then boostrap AboutComponent
I am doing it by implementing ngDoBootstrap method as following.
export class AppModule {
url : string;
constructor(#Inject(DOCUMENT) private document: any){
this.url = this.document.location.href.toLowerCase();
}
ngDoBootstrap(app:ApplicationRef){
if(this.url.indexOf("home.aspx") > 0){
app.bootstrap(HomeComponent);
}
else if(this.url.indexOf("about.aspx") > 0){
app.bootstrap(AboutComponent);
}
}
}
This is how based on page url, we can dynamically bootstrap our Component and save a lot files of main.ts and app.component.ts for each page.
For this, you need to add entry for each component into entryComponents array of NgModule as below:
#NgModule({
entryComponents : [
HomeComponent,
AboutComponent,
]
})
Hope this helps.

change your index.html base route to your webpage
<base href="/YourWebPageRoute">
include the page inside the webform
<% Response.WriteFile("index.html"); %>

Related

Next.js _app and _document use?

I'm totally new with next.js and I need your help for something I guess really basic but I cannot find my mistake or an explanation, I found nothing on the internet about it, so here I am :
Everything works when I create a file in the pages folder(I mean every file in pages folder is ok except _app.js or _document.js), I can reach the URL, but I would like to use context, layout or authentification in the future and I need to use the _app and _document override cool things but I can write anything I want in it, it seems my _app.js or _document.js are just useless, never called or I don't know but they just never work.
I tried on 2 projects, here is what I do according to the next documentation :
first, npx create-next-app to create the project, and then add an _app.js for example in pages folder and add :
import React from 'react'
import App from 'next/app'
import Nav from '../components/nav'
class MyApp extends App {
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// static async getInitialProps(appContext) {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }
render() {
const { Component, pageProps } = this.props
return (
<>
<Nav />
<Component {...pageProps} />
</>
);
}
}
export default MyApp
Anybody could tell me what I am doing wrong?
Well, if anybody is going through the same issue, I found what was going on, in fact, after creating for the first time _app.js, I have to restart my docker container, or restart my app with yarn next dev if I want to see the changes or they never appear. I am going to look for more explanations on how SSR and next.js more globaly exactly work to understand their behaviour on this point. Good luck all !

Create Route to Simple Page Reaction Commerce

I am trying to setup a simple static page for about us, based on this tutorial (https://docs.reactioncommerce.com/reaction-docs/master/plugin-routes-6). The problem is that there is no real explanation on what I need to do outside adding an entry to the registry.js file. While they do have the plugin example that I could copy, I would like to know what I need to just add a simple static page to Reaction Commerce. Thanks.
Wade
To create the simple route for the page, given tutorial is what we all got.
To Create route for a page:
I will break it down for you in following steps:
I will assume that you know we have to add our code in the /imports/plugin/custom directory only. You can override all the core functionality from here.
Let's get started:
You need to add route details in the registry under register.js file.
registry:[
{
route:"/about",
name:"about",
template:"aboutUs",
workflow:"coreWorkflow"
}
],
Create the component for a new page as
/imports/plugin/custom/YOUR_PLUGIN/client/components/about.js in your plugin.
import React, { Component } from "react";
import { registerComponent } from "/imports/plugins/core/components/lib";
import { Meteor } from "meteor/meteor";
import { Col } from 'reactstrap';
class About extends Component {
render() {
return (
<div className="container-main">
About Us Page
</div>
);
}
}
registerComponent("about", About);
Add the button to route to the new page, in any component, from where you can give link to About page.
<Components.Button
label="About"
onClick={handleClick}
/>
Add function to handle the click.
handleClick() {
return Reaction.Router.go("/about");
}
Hope this solves your query!
PS: I know this code can be shortened, I have written it in this way so that beginners can understand it faster. Please don't hesitate to correct the answer if I am wrong. :)

METEOR: how to redirect after logout

I am quite new to Meteor & React. Here I would like to redirect my currect user to home page whenever the logout button is pressed. Attached you can see the protected page template with the logout button.
Please note that I am working with the latest versions (Meteor 1.6.1 and React V4).
import React from 'react';
import { Accounts } from 'meteor/accounts-base';
export default class Link extends React.Component{
onLogout(){
Accounts.logout()
};
render(){
return(
<div>
<p>Private Content goes here</p>
<button onClick={this.onLogout.bind(this)}>Logout</button>
</div>
);
}
};
any kind of support will be appreciated.
There are two main options to use here:
1. Pass a callback to Accounts.logout(func)
This is the simplest but mixes the return behavior into your component, which is not ideal.
2. Use Accounts.onLogout(func)
You could put this with your accounts initialization or with your router code, whichever keeps the logic grouped together best for your app.
In that callback, you'll want to use your router to redirect. The exact syntax will depend on your router, but will generally look like:
Router.go('/')
Another way, if you are setting things via meteor-useraccounts way...
const myLogoutFunc = function() {
FlowRouter.go('/login');
}
AccountsTemplates.configure({
// Hooks
onLogoutHook: myLogoutFunc,
onSubmitHook: mySubmitFunc,
preSignUpHook: myPreSubmitFunc,
postSignUpHook: myPostSubmitFunc,
});
Template event code is something like this..
'click .logout': () => {
AccountsTemplates.logout();
}
Read in detail here https://github.com/meteor-useraccounts/core/blob/master/Guide.md

Meteor 1.3 - lazy loading or evaluation of files

I am very excited with ES2015 modules in Meteor 1.3. We have written an app with medium complexity with Meteor 1.2. As we have very large number of templates and files, it is taking a bit of time to download the content on client side. so I am interested in the lazy loading feature using import. From the meteor night talk, they say that the Blaze templates are still global and cannot be imported (or lazy loaded), I have tried using React inside Blaze.
Added react-template-helper package using meteor add react-template-helper
Create imports folder and added testComponent.jsx file which exports 'TestComponent'
//testComponent.jsx
import React from 'react';
export default class TestComponent extends React.Component {
render() {
return (
<div>
<h1>TestComponent</h1>
<div>This is from Test Component</div>
</div>
);
}
}
After in the Blaze template outside imports folder,
<!-- homeReact template html-->
<template name="homeReact">
<div>
{{> React component=TestComponent}}
</div>
</template>
In the template's js file which is also outside of imports folder
// homeReact template js
import { Template } from 'meteor/templating';
import TestComponent from '/imports/testComponent.jsx`;
Template.homeReact.helpers({
TestComponent() {
return TestComponent;
}
});
This worked but the imports/testComponent.jsx is downloaded on the client (checked using chrome dev tools - sources tab), even if the current route doesn't require homeReact template.
Then I have used require instead of import like this,
// homeReact template js
import { Template } from 'meteor/templating';
Template.homeReact.onCreated(function () {
this.TestComponent = require('/imports/testComponent.jsx').TestComponent;
});
Template.homeReact.helpers({
TestComponent() {
return Template.instance().TestComponent;
}
});
This code also downloads the imports/testComponent.jsx file but in addition I also got an error
In template "homeReact", call to {{> React ... }} missing component argument.
So, my question is, is it possible to lazy load (download) files only when required?

Initializing react component from asp.net

Hopefully this is a slam-dunk for someone out there...my essential problem is this: I've built up a very nice set of react components which i can render in my asp.net 4.5 mvc 6 application using react.js, flux, gulp, and browserify.
as long as i have it structured so that the react components have all the data they need everything is perfect. My issue now is that I would like to have an MVC view include the react stuff, and inject run-time properties into the top-level component as it is created. Since I'm brpowserify-ing all of my react code into a bundle, i just include the one script tag in my view:
<script src="/js/modules/AuthContainer.jsx"></script>
But whereas I would normally use JSX syntax to instantiate my component with props like this:
...the view in ASP.NET never gets translated to pure JS, so that fails.
I've also tried:
ReactDOM.render
(
React.createElement(AuthContainer, { successPath: '/home' }),
document.getElementById('reactRoot')
);
...from inside a script block in my view but i get:
Uncaught ReferenceError: AuthContainer is not defined
But i'm sure i'm exposing 'AuthContainer' via the browserify-ed bundle, so i don't understand why it's unable to resolve that component.
I know there's a React.NET way to do this, but i can't get that server-side rendering to work with my components because I'm using jQuery to fetch data in componentDidMount and the server-side rendering is choking looking for $() jQuery stuff.
I'd love to get the server side rendering going but right now i just need it to do work, one way of the other. Can someone provide a simple code snippet or gist of how to instantiate a React component from inside a cshtml file with run-time props?
One easy solution is this, just put your server side properties with Javascript in a global:
index.cshtml
<script>
var __config__ = {
base: "#MyBackEdnVariable",
initialCount: "#Count",
user: {
id: #user.id,
name: #user.name,
}
};
</script>
<script src="/js/modules/AuthContainer.jsx"></script>
And with React use that global variable:
AuthContainer.js
class AuthContainer extends React.Component {
render() {
return (
<div>{this.props.user.name}</div>
);
}
}
AuthContainer.defaultProps = {
initialCount: __config__.initialCount,
user: __config__.user
};
For posterity:
ReactDOM.render
(
React.createElement
(
MyComponent,
{
prop1: #numericValue,
prop2: '#textValue',
}
),
document.getElementById('reactRoot')
);
the magic was the jsx-alternative syntax, which i was aware of couldn't get a handle on that day. This allows you to instantiate react using pure JS and therefor just embed inside a simple script tag in your cshtml.
hth.

Resources