Angular1.x and angular2 together - javascript

Is there any problem to use angular2 in a website that uses angular 1.x theme (HTML theme develeoped using angular 1.x).
Any challenges need to be faced while developing?

You can use Angular (Angular2) components inside an AngularJs (Angular1) application by using downgradeComponent function of upgrade module. Check this documentation link.
import { HeroDetailComponent } from './hero-detail.component';
/* . . . */
import { downgradeComponent } from '#angular/upgrade/static';
angular.module('heroApp', [])
.directive(
'heroDetail',
downgradeComponent({component: HeroDetailComponent}) as angular.IDirectiveFactory
);

Related

Using downgradeModule in conjunction with downgradeInjectable in an angular / angularjs hybrid application results in error

With angular 5.0 the upgrade module now has the option of using downgradeModule which runs angularjs outside of the angular zone. While experimenting with this I have run into a problem with using downgradeInjectable.
I am receiving the error:
Uncaught Error: Trying to get the Angular injector before bootstrapping an Angular module.
Bootstrapping angular in angular js works fine
import 'zone.js/dist/zone.js';
import * as angular from 'angular';
/**
* Angular bootstrapping
*/
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { decorateModuleRef } from 'src/environment';
import { AppModule } from 'src/app/app.module';
import { downgradeModule } from '#angular/upgrade/static';
export const bootstrapFn = ( extraProviders ) => {
const platformRef = platformBrowserDynamic( extraProviders );
return platformRef
.bootstrapModule( AppModule )
.then( decorateModuleRef );
};
angular.module( 'app.bootstrap', [
downgradeModule( bootstrapFn ),
] );
However...
Since the bootstrapping takes place after angularjs has been initialized I can no longer get the downgrade injectable working.
Service to be downgraded
import { Injectable, Inject, OnInit } from '#angular/core';
#Injectable()
export class MobileService implements OnInit{
constructor(
#Inject( 'angularjsDependency1' ) public angularjsDependency1 : any,
#Inject( 'angularjsDependency2' ) public angularjsDependency2 : any,
) {}
}
Downgrade injectable attempt
import * as angular from 'angular';
import { downgradeInjectable } from '#angular/upgrade/static';
import { MyService } from 'src/services/myService/myService';
export const myServiceDowngraded = angular.module( 'services.mobileService', [
angularjsDependency1,
angularjsDependency2,
] )
.factory(
'mobileService',
downgradeInjectable( MyService ),
).name;
When "downgradeInjectable( MyService ) runs the angular injector is not available yet since angular hasn't been bootstrapped. Hence the error:
Uncaught Error: Trying to get the Angular injector before bootstrapping an Angular module.
Does anyone have an idea how I might fix this?
Answers in this thread helped me find a solution, but none contains the holy grail:
Creating a service-boostrap component aside the app's code does not work, because Angular is loaded asynchronously, unlike AngularJS. This gives the same error Trying to get the Angular injector before bootstrapping an Angular module.
Creating a service-bootstrap component wrapping the AngularJS code kind of worked, but then I experienced issues with change detection inside Angular composants, as described in this issue on github.
In the github issue, someone suggested to edit #angular/upgrade source code to change a false to true to force components to be created in the Zone. But in this case it seems to cause performance issues (it seemed to launch ngZone's code multiple times on user events)
In order for the app to work correctly, I needed :
Not to have ng components containing AngularJS components containing Angular components. We need to only have AngularJS containing Angular components.
Make sure that AngularJS components using Angular services are created after a first angular component, named service-bootstrap
To acheive this, I created a slightly modified service-bootstrap component:
import { Component, Output, EventEmitter, AfterViewInit } from "#angular/core";
#Component({
selector: 'service-bootstrap',
template: ``
})
export class ServiceBootstrapComponent implements AfterViewInit{
#Output()
public initialized: EventEmitter<void> = new EventEmitter();
public ngAfterViewInit(){
this.initialized.emit();
}
}
Declared this component as entryComponent in the Angular module and called downgradeComponent to register it in AngularJS:
import { downgradeModule, downgradeInjectable, downgradeComponent } from '#angular/upgrade/static';
const bootstrapFn = (extraProviders: StaticProvider[]) => {
const platformRef = platformBrowserDynamic(extraProviders);
return platformRef.bootstrapModule(AppModule);
};
const downgradedModule = downgradeModule(bootstrapFn);
const app = angular.module('ngApp', [
downgradedModule,
'app'
]);
app.directive('serviceBootstrap', downgradeComponent({ component: ServiceBootstrapComponent }));
Then (and the magic happens here), I created a new AngularJS component:
angular.module("app")
.directive('ng1App', ng1AppDirective);
function ng1AppDirective(){
return {
template: `
<service-bootstrap (initialized)="onInit()"></service-bootstrap>
<section ng-if="initialized">
<!-- Your previous app's code here -->
</section>
`,
controller: ng1AppController,
scope: {},
};
}
ng1AppController.$inject = ['$scope'];
function ng1AppController($scope){
$scope.onInit = onInit;
$scope.initialized = false;
function onInit(){
$scope.initialized = true;
}
}
Then, my index.html only referenced this component
<body>
<ng1-app></ng1-app>
</body>
With this approach, I'm not nesting AngularJS components inside Angular components (which breaks change detection in Angular components), and still I ensure that a first Angular component is loaded before accessing the Angular providers.
Note: The answer below follows the convention of calling angular 1.x as angularjs and all angular 2+ versions as simply angular.
Expanding on JGoodgive's answer above, basically, if you're using downgradeModule, then angular module is bootstrapped lazily by angularjs when it needs to render the first angular component. Until then, since the angular module isn't initialised, if you are accessing any angular services inside angularjs using downgradeInjectable, those services aren't available too.
The workaround is to force bootstrapping of the angular module as early as possible. For this, a simple component is needed:
import {Component} from '#angular/core';
#Component({
selector: 'service-bootstrap',
template: ''
})
export class ServiceBootstrapComponent {}
This component doesn't do anything. Now, we declare this component in the top level angular module.
#NgModule({
// ...providers, imports etc.
declarations: [
// ... existing declarations
ServiceBootstrapComponent
],
entryComponents: [
// ... existing entry components
ServiceBootstrapComponent
]
})
export class MyAngularModule {}
Next, we also need to add a downgraded version of this component to angularjs module. (I added this to the top level angularjs module I had)
angular.module('MyAngularJSModule', [
// ...existing imports
])
.directive(
'serviceBootstrap',
downgradeComponent({ component: ServiceBootstrapComponent }) as angular.IDirectiveFactory
)
Finally, we throw in this component in our index.html.
<body>
<service-bootstrap></service-bootstrap>
<!-- existing body contents -->
</body>
When angularjs finds that component in the markup, it needs to initialise angular module to be able to render that component. The intended side effect of this is that the providers etc. also get initialised and are available to be used with downgradeInjectable, which can be used normally.
This was pointed out to me in an angular github thread.
https://github.com/angular/angular/issues/16491#issuecomment-343021511
George Kalpakas's response:
Just to be clear:
You can use downgradeInjectable() with downgradeModule(), but there are certain limitations. In particular, you cannot try to inject a downgraded injectable until Angular has been bootstrapped. And Angular is bootstrapped (asynchronously) the first time a downgraded component is being rendered. So, you can only safely use a downgraded service inside a downgraded component (i.e. inside upgraded AngularJS components).
I know this is limiting enough that you might decide to not use downgradeInjectable() at all - just wanted to make it more clear what you can and can't do.
Note that the equivalent limitation is true when using an upgraded injectable with UpgradeModule: You cannot use it until AngularJS has been bootstrapped. This limitation usually goes unnoticed though, because AngularJS is usually bootstrapped in the Angular module's ngDoBootstrap() method and AngularJS (unlike Angular) bootstraps synchronously.
I had the same issue, and the reasons are explained in the above answer.
I fixed this by dynamically injecting the downgraded angular service using $injector.
Steps
Register your downgraded service to angularjs module
angular.module('moduleName', dependencies)
angular.factory('service', downgradeInjectable(Service));
Inject $injector to your controller and use this to get the downgraded service
const service = this.$injector.get('service');
service.method();
I had the same issue and it sucked up several hours before finding this.
My workaround was to create a ServiceBootstrapComponent that does nothing but injects all the services that we need to downgrade.
I then downgrade that component, mark it as en entry in #NgModule and add it to index.html.
Works for me.
I was getting the same error in our hybrid app. We are using the following versions:
AngularJS 1.7.x
Angular 7.3.x
As mentioned in this answer, I also used a dummy component called <ng2-bootstrap> to force boostrapping of Angular. And then, I created an AngularJS service which checks if Angular has been bootstrapped:
// tslint:disable: max-line-length
/**
* This service can be used in cases where Angular fails with following error message:
*
* `Error: Trying to get the Angular injector before bootstrapping the corresponding Angular module.`
*
* Above error occurs because of how `downgradeModule` works.
*/
/*#ngInject*/
export class Ng2BootstrapDetectionService {
private bootstrapDone = false;
constructor(private $q: ng.IQService) {}
public whenBootstrapDone(): ng.IPromise<void> {
if (this.bootstrapDone) {
return this.$q.resolve();
}
const deferred = this.$q.defer<void>();
angular.element(document).ready(() => {
const intervalId = setInterval(() => {
const el = document.querySelector('ng2-bootstrap');
if (el && el.outerHTML.includes('ng-version=')) {
this.bootstrapDone = true;
clearInterval(intervalId);
deferred.resolve();
}
}, 500);
});
return deferred.promise;
}
}
Ng2BootstrapDetectionService can be used like below:
import {NotificationService} from 'ng2-app/notification.service';
// This can be used in cases where you get following error:
// `Error: Trying to get the Angular injector before bootstrapping the corresponding Angular module.`
// You will need access to following
// $injector: AngularJS Injector
// Ng2BootstrapDetectionService: our custom service to check bootsrap completion
this.Ng2BootstrapDetectionService
.whenBootstrapDone()
.then(() => {
const notificationService = this.$injector
.get<NotificationService>('ng2NotificationService');
notificationService.notify('my message!');
});
You can find more details about this solution at the end of this blog post.

How do I declare a dependency on an ng-metadata module?

I have a project that is using ng-metadata (https://github.com/ngParty/ng-metadata) to build a handful of Angular 1.5 modules. I have a test module/component that looks like this:
import { NgModule, Component, Inject, Input, Output, EventEmitter } from 'ng-metadata/core'
import { platformBrowserDynamic } from 'ng-metadata/platform-browser-dynamic'
#Component({
selector: 'test',
template: require('./test.template.html')
})
class TestComponent {
#Input() type: string;
constructor() {
console.log(`test: ${this.type}`)
}
}
#NgModule({
declarations: [TestComponent]
})
class HeroModule {}
platformBrowserDynamic().bootstrapModule(HeroModule)
Everything seems happy when compiled and I'm now attempting to use the module in another project (that is not using ng-metadata but has a compatible version of Angular).
I'm simply including the shims as directed by the ng-metadata docs and the JavaScript file that contains the module described above (built by webpack). I have a new module in this project that wants to list the HeroModule as a dependency. I've tried a few things:
// attempt 1:
angular.module('my-consuming-module', ['ui.router', 'hero'])
// attempt 2:
angular.module('my-consuming-module', ['ui.router', 'heroModule'])
// attempt 3:
angular.module('my-consuming-module', ['ui.router', 'hero-module'])
All always end up with the same Error: $injector:nomod Module Unavailable error from Angular.
If I'm using ng-metadata to build my modules, what are the names I use to list them as dependencies in another project?
Finally figured this out! It's amazing what happens when you carefully read documentation...
Found in the Manual Angular 1 Bootstrap section of ng-metadata's docs:
You can still leverage ng2 way of components registration without ng-metadata bootstrap, but you have to manually create your Angular 1 module from an ng-metadata #NgModule using the bundle helper function.
I ended up being able to do the following:
// REMOVED platformBrowserDynamic().bootstrapModule(HeroModule)
const Ng1AdminModule = bundle(HeroModule).name;
export const AppModule = angular.module('hero', [Ng1AdminModule]);
And then my hero module becomes accessible to the my-consuming-module just as I expected. The bundle helper function was the key to figuring this out.
You need to import those module from their respective locations and inject it inside your angular module
//ensure `angular`, `angular-ui-router` should be there in `map` of systemjs.config.js
import * as angular from 'angular';
import * as uiRouter from 'angular-ui-router';
import { heroModule} from './hero.module';
angular.module('app',[ uiRouter, heroModule]);
Check references here

angular material design with typescript

I am brand new to typescript, typings. Vaguely understand type definition and trying to setup angular 1.5 project with typescript and angular material design.
I have angular material type definition in typings>globals>angular-material.
I don't know what module I can import and where to check. If i put like the following example, i get an exception: Module 'material' is not available!
import * as angular from 'angular';
import * as material from 'angular-material';
angular.module('app.services', []);
angular.module('app', ['app.services', 'material']);
The top portion of index.d.ts in typings>globals>angular-material is
declare module 'angular-material' {
var _: string;
export = _;
}
declare namespace angular.material { ...}
Thanks in advance.
It should be like this,
angular.module('app.services', []);
angular.module('app', ['app.services', 'ngMaterial']);
You should not import from 'angular-material'
just add a reference to typings :
/// <reference path="../typings/angular-material/angular-material.d.ts" />
(be sure to install typings for angular-materials first)
then use :
angular.module('app.services', []);
angular.module('app', ['app.services', 'ngMaterial']);
You should remove the single quotes when defining material provider for example
import * angular from 'angular';
import * as material from 'angular-material';
angular.module('app.services', []);
angular.module('app', ['app.services', material]);
This will solve your issue.
Also for importing material style sheet you can use following code.
import 'angular-material/angular-material.css';
For libraries that don't have type definitions you can use the following code.
import * as angular from 'angular';
require('../../../node_modules/angular-messages');
angular.module('app.services', []);
angular.module('app', ['app.services', 'ngMessages']);
Note : Here you should use string for defining provider
Small, I hope useful, addition (the experience I faced recently). If you need to use angular-material in TS unit tests, you will need to import it into spec file too (whereas in main code you only need to import it once and set as dependency in main module). Then it's sufficient to import 'angular-material'; at the top, and add variable for necessary service with corresponding typings, e.g. let dialog:ng.material.IDialogService;

How to convert angularJS version 1.X controller into angular 2.X using EM6 ngupgrade

angular.module('app', []).controller('MessagesCtrl', function() {
$scope.self.list = [
{text: 'Hello, World!'},
{text: 'This is a message'},
{text: 'And this is another message'}
];
self.clear = function() {
$scope.self.list = [];
};
});
this is a controller written in angular. how can I convert this into angular 2 using EM6.
well upto my knowledge there are not alot of tutorials for the upgradation but yes thetre are few one.
https://angular.io/docs/ts/latest/guide/upgrade.html
http://blog.thoughtram.io/angular/2015/10/24/upgrading-apps-to-angular-2-using-ngupgrade.html
well let me tell you about basic angular2 app.
in angular 1.x our main module is initilize like this
angular.module('app', [])
but in the angular2 our main component started from the bootstraped file like this.
import {bootstrap} from 'angular2/platform/browser';
import {App} from './app';
bootstrap(App,['here global level dependenices....']);
here app is our main component whihc is imported in this bootstrap file. so bootstraped is file our entry point of the app. and
if we want to do some coding stuff like we work in the angular1.x controller here we do the same work in the class file (typescript class)
here i am posting one basic example like this.
import {Component, View} from 'angular2/core';
#Component({
selector: 'app',
templateUrl: "src/app.html",
styleUrls: ['src/app.css'],
directives: [ directives list here....],
})
export class App
{
// stuff you want to do here
}
firstly we have to import angular2 bundles from the systemjs bundles like we imported Component and view in this example from the angular2/core.
there are alot of imports available for the angular2. you can check out here and here

How to use react custom package into an angular directive

Hi i have an angular v1.x application and a react custom package.
I want to be able to use the react custom package into the angular directive, which eventually will display a react component.
some code:
angular app:
directive that consumes the my-package
import app from '../../main'
import React from "react";
import ReactDOM from "react-dom";
import Mypackage from 'my-package';
const reactDirective = app.directive('injectReact', function() {
return {
template: '<div id="reactapp" class="react-part"></div>',
scope: {},
link: function(scope, el, attrs){
scope.newItem = (value) => {alert (value)}
const reactapp = document.getElementById('reactapp')
scope.$watch('scopeval', function(newValue, oldValue) {
if (angular.isDefined(newValue)) {
ReactDOM.render(
<div>
<Mypackage />
</div>
, reactapp);
}
}, true);
}
}
})
The package is linked into the project, so 'my-package' is inside angular's node_modules folder.
The application uses bower & gruntfile.js to gother all the js files of the application
i cant use import or require into the directive file.
so i miss some babel/browserify configuration to make this work.????
Any help is welcome.
The easiest way you can achieve this is by using external package like react2angular. This package allows you to create angular.js wrapper components which will render specific react components, allowing you to pass props to them. Linking process is quite simple:
angular
.module('myModule', [])
.component('myComponent', react2angular(MyComponent, [], ['$http', 'FOO']))
If you want to create you own wrapping library checkout how it's made here (rendering, passing props and watching for changes to them)

Categories