Skip to main content

Posts

Conflicting styles with multiple Angular apps in the same page

About two years ago I was gradually converting an old web app to modern Angular. At some point the app was in a state were the Angular components were embedded as multiple apps at different locations in the page. Very soon I found that one app got the css styling rules from the other, and that the APP_ID that was supposed to be present in the generated html/css (according to the docs:  https://angular.io/guide/component-styles#inspecting-generated-css ) was not there. I made a fix for this, and a pull request to Angular and am very happy now see that my fix for this is finally included here So now you should also be able to use Angular for creating multiple standalone widgets, adverts in any web page that is not made in Angular. That could be news sites, blogs, portals or anything. Angular just got new significant areas of use

Webassembly and audioworklet

Have been playing a lot recently with webassembly and the upcoming audioworklet web standard. This is exciting and powerful technology, opening up for serious use of the web in production of audio and music. Follow the links from my homepage petersalomonsen.com for live demo and more resources.

Using Angular i18n translation strings outside templates

As of today in Angular 6 i18n is only available in the templates. So what if we want to use translated messages programatically and outside templates? I still use the component template html file to declare the message to be translated, but by obtaining the TemplateRef ViewChild in the component typescript file I can get the translated messages from typescript. <ng-template #boardInvitationEmailBody let-organization="organization" let-url="url"> <ng-container i18n>You have been invited to join the board portal for</ng-container> {{organization}}. <ng-container i18n> Please follow the link to: </ng-container> {{url}} </ng-template> So in the typescript code i can now call the createEmailBodyTranlated text method to get the translated text for use outside the template. @ViewChild('boardInvitationEmailBody') boardInvitationEmailBody: TemplateRef ; createEmailBodyTranslatedText(org...

Using GIT for offline web app syncing and storage

Offline web applications, progressive web apps (PWA) using service workers for being available offline also needs a way to sync changes with the server. Mostly we store data in JSON documents, and we could identify changes per line - which is something GIT is excellent at. So how could we make the browser a GIT client? I've been working on this for some months now, and compiled libgit2 to webassembly using emscripten - and it turns out to work very well. Some video demos: Cloning a repository: https://youtu.be/rcBluzpUWE4 Merging of file changes: https://youtu.be/xfGrMwLy_tw The project is here: https://github.com/fintechneo/angular-git-filebrowser

Angular for Java EE developers

Being a Java EE developer for a long time and trying to find a development platform in these times where more and more business logic is placed in the frontend code, Angular (NOT AngularJS) became a natural choice. Being used to Java Server Faces with backend beans, coding with Angular is quite similar. You still have a HTML template and a separate class (Angular components ) with the template logic, but now this is all part of the frontend code. Also quite a bit of the code you would earlier place in EJB session beans can be put in Angular services , which can be injected into components using dependency injection . All together with TypeScript which gives you static types, decorations (annotations), classes and interfaces that any Java developer will miss when coding with Javascript. Now that the client / frontend does more and more of the traditional backend work, and the backend is more about providing data and access control than application business logic - Angular is a f...

Angular components not reloading on route change

Spent a long time wondering why route changes caused strange effects on my component, and found out that it was because my component wasn't reloading at all. I had this assumption that when a route parameter changed (e.g. /projects/1 changed to /projects/2 ) the component for the route would be reloaded. But this is not the default behaviour of the Angular router. The default behaviour of the Angular router is to reuse the route if the configuration is the same (and not reload the component). But we can override this by providing a RouteReuseStrategy to our @NgModule: providers: [ { provide: RouteReuseStrategy, useClass: AARouteReuseStrategy } ] The full custom implementation of the RouteReuseStrategy will then be like this (and it's the shouldReuseRoute method that changes the behaviour so that the component is reloaded on route parameter change): export class AARouteReuseStrategy extends RouteReuseStrategy { shouldDetach(route: ActivatedRou...

Multiple router outlets in Angular

Multiple router outlets in Angular makes it possible to have different sections in the view where the components are determined by the URL, and each outlet can have their own navigation. Sometimes though - let's say you use named router outlets for the toolbar and the left side menu, you want the main URL to control the components to be showed for all outlets, not just the main outlet. In this case the router outlet configurations should be children on the main path as shown in the config snippet below. This way the URL /projects/2018/myorganization will show a left side menu and a toolbar in addition to the main content component, while /projects/2018 will only show the toolbar. If you want the toolbar only to show at the projects root path, but not children then add pathMatch: 'full' . RouterModule.forChild([ { path: 'projects', children: [ { path: '', ...

Angular 5 - Ahead of Time build configuration for rollup

Earlier the @angular Ahead of Time compilation cookbook showed you the compilation steps using the @angular/compiler-cli (ngc) and rollup. From Angular 5 it seems to be all about the Angular CLI (using ng build --prod). In some cases though it's nice to have the rollup recipe. We also want to benefit from the build optimizer and rxjs esm module which is default in Angular 5. So I've written down the configuration steps here for building a rollup-based AoT build for Angular 5. The typescript configuration for the @angular/compiler-cli (ngc). Store in file tsconfig_aot.json. { "compilerOptions": { "outDir": "js", "module": "es2015", "moduleResolution": "node", "target": "es5", "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": [ "dom", "es2017"...

Creating Angular libraries

When your app grows and you make components that could be reused in other apps it's a good thing to split out that code in a library. Also if your app is big already and someone else is going to add a new feature to it, it's much easier if they can work on that feature in a small isolated project and when ready import it into the main app as a library. The architecture of Angular with modules  help us organize the application code into blocks of functionality. The step of splitting into libraries should build on that, but add the benefits of not having to see code not relevant to the modules we're currently working on and to easily install and reuse in several applications without having to duplicate code across projects. Creating an Angular library is basically about packaging compiled NgModules into a format that can be installed into another application using a package manager like npm. It could be done as easily adding the typescript sources and html templates to a ...

Create PDF's in Angular / Typescript

Posting an example of how to create PDFs directly in the browser with no server involved using Angular, Typescript and pdfmake.org . The demo is here:  https://fintechneo.github.io/angular2-templates/ The PDF creation is initiated in the createPDF() method of this source:  https://github.com/fintechneo/angular2-templates/blob/master/app/pages/accountreportcomponents.ts The pdfmake library is made available to Angular and Typescript by creating a script element inside an rxjs/Observable that is notified on the script element onload. You can see how it's done in here:  https://github.com/fintechneo/angular2-templates/blob/master/app/pdfmake/pdf.service.ts

Simple Firebase service for Angular 2

If you want a very simple alternative to Angularfire you may create a firebase service very easily. I made this to avoid extra configuration when it comes to adding npm packages and configuring for bundling. This is done by downloading the scripts from Firebase CDN directly by using a dynamically created script tag. Once the service is initialized you'll find the database in the public database property, and you just use the regular Firebase API. (Example: this.fbservice.database.ref('someproperty').set(somevalue) - and remember to have fbservice : FireBaseService in your component constructor to inject the service. ) And here's the code for the service: import { Injectable } from '@angular/core' ; import { Observable } from 'rxjs/Observable' ; declare const firebase : any ; const config = { apiKey : " " , authDomain : " .firebaseapp.com" , databaseURL : " " , storageBucket : ...

My VNC based development environment with Visual Studio Code running on Ubuntu

I've used this setup for my development environment for several years - giving me a developer desktop I can access anywhere. Even from my mobile phone. I've been fixing bugs, writing code and deployed emergency fixes from the bus, train and mountain tops. The setup is based on a lightweight desktop environment. There are lot of alternatives, but I've chosen fluxbox. From a plain AWS Amazon Ubuntu 16.04 ec2 instance I've started like this: sudo apt-get update sudo apt-get install fluxbox Download and extract tigervnc from https://github.com/TigerVNC/tigervnc/releases (I downloaded the binary file from https://bintray.com/tigervnc/stable/tigervnc/1.7.0 named tigervnc-1.7.0.x86_64.tar.gz ) then extract: tar -xvzf tigervnc-1.7.0.x86_64.tar.gz You need to install: sudo apt-get install x11-xkb-utils You need to edit .vnc/xstartup: nano .vnc/xstartup last line replace "twm &" with: fluxbox & Then you can start the...

Secure file transfer with Java and Versile

Just made an example of how to transfer a file over a secure and authenticated connection in pure Java - without having to use additional technology like ssh/scp. Versile has all you need for creating a secure and authenticated connection, and you'll decide what files you want to expose - nothing more - nothing less. This is the file server (include versile.jar in your classpath - and create a file called "personregister.txt" in the working directory): package versileexample; import java.io.File; import java.io.FileNotFoundException; import java.io.RandomAccessFile; import java.security.interfaces.RSAPublicKey; import java.util.logging.Level; import java.util.logging.Logger; import org.versile.Versile; import org.versile.common.auth.VAuth; import org.versile.common.auth.VCredentials; import org.versile.common.auth.VPrivateCredentials; import org.versile.common.peer.VInetSocketPeer; import org.versile.common.peer.VPeer; import o...

Converting from linear to logarithmic scale

A simple function useful to plot a logarithmic scale. Just provide it with the min and max values of the scale and the value you want to convert - and you'll get in return a value as it should be positioned on a logarithmic scale in the given range. public double toLogScale(double min, double max,double val) { double logmin = Math.log(min); double logmax = Math.log(max); double logscale = (Math.log(val)-logmin) / (logmax-logmin); return min+(max-min)*logscale; }

Ubuntu desktop in the cloud accessible with VNC

To create a Ubuntu desktop on Amazon EC2 that can be accessed by VNC I did the following steps: 1. Create 64-bit Ubuntu server instance 2. Install ubuntu desktop: sudo apt-get install ubuntu-desktop 3. Install x11vnc sudo apt-get install x11vnc 4. Install xvfb sudo apt-get install xvfb 5. Configure x11vnc sudo nano /etc/init/x11vnc.conf start on login-session-start script /usr/bin/x11vnc -xkb -auth /var/run/lightdm/root/:0 -noxrecord -noxfixes -noxdamage -rfbauth /etc/x11vnc.pass -forever -bg -rfbport 5900 -o /var/log/x11vnc.log end script And you should also set a password for your vnc sessions: sudo x11vnc -storepasswd /etc/x11vnc.pass 6. Configure X server to use xvfb: (Add the xserver-command line) sudo nano /etc/lightdm/lightdm.conf [SeatDefaults] greeter-session=unity-greeter user-session=ubuntu xserver-command=/etc/X11/xinit/xserverrc (Replace the exec line) sudo nano /etc/X11/xinit/xserverrc #!/bin/sh #exec /us...

Exporting Kendo UI GRID to Excel with Java

This is a simple method of creating an Excel export function on your Kendo UI grid with a Java EE server. JS function to trigger Excel export In your web-page with the grid - insert this JS function. You should create a button or similar that calls this when you want to perform the export from the UI. function exportGridToExcel() { var grid = $("#grid").data("kendoGrid"); var currentPage = grid.dataSource.page(); var allPages = new Array(); for(var n=1;n<=grid.dataSource.totalPages();n++) { grid.dataSource.page(n); var view = grid.dataSource.view(); for(var x=0;x<view.length;x++) { allPages.push(view[x]); } } $("#excelExportGridData").val(JSON.stringify({"rows": allPages, "cols": grid.columns})); $("#exportToExcelForm").submit(); grid.dataSource.page(currentPage); } Hidden form and iframe You also nee...

IOS Java App (RoboVM) communicating with server (Versile)

Before you continue - check out the demonstration video: The demonstration uses RoboVM to build an IOS app (written in Java), and Versile  to create a server and provide communication between the app and server. Details of configuring Versile and RoboVM are not described here. Go to RoboVM website, and check my earlier Versile blog posts for more info. The source for the IOS app is based on the RoboVM example: import java.util.Date; import org.robovm.cocoatouch.coregraphics.*; import org.robovm.cocoatouch.foundation.*; import org.robovm.cocoatouch.uikit.*; import org.robovm.objc.block.VoidBlock; import org.robovm.rt.bro.Bro; import org.robovm.rt.bro.NativeObject; import org.robovm.rt.bro.annotation.Bridge; import org.robovm.rt.bro.annotation.Library; import org.versile.Versile; import org.versile.orb.entity.VProxy; import org.versile.reactor.url.VUrl; import org.versile.vse.VSEResolver; import org.versile.vse.util.VFunction; public class VersileRoboVM...

Remote service interaction with Versile and Groovy - Part 2

In the previous post I showed you how to connect two peers using Versile. In this post I'll show how to authenticate the party requesting the connection. Authentication in Versile is done by checking the public key received from the other party. Both sides can check the identity of the other side. Identity key pairs can be generated using Versile Decentral Identity ( VDI ), which in many ways is similar to SSH-keygen. Using VDI is as simple as usernames and passwords, but not having to share this with the other party increase security - and the keys can be exchanged privately between the two parties, no certificate authority needs to be involved. A Versile Decentral Identity can be generated from Groovy/Java as simple as this: VPrivateCredentials key = new VPrivateCredentials(VDecentralIdentity.dia(1024, 'versilegroovy', 'peter', 'asdfghjkl12345')) And we can print the public key: print new String(key.getKeyPair().exportPublicArmoredPkcs()) ...