198 Lotus blogs updated hourly. Who will post next? Home | Blogs | Search | About 
 
Latest 7 Posts
Deploying MicroProfile based Java Applications to Bluemix
Fri, Sep 22nd 2017 3
Deploying MicroProfile based Apps to IBM Cloud private
Thu, Sep 21st 2017 45
Watson Machine Learning Sample Walkthrough
Tue, Sep 19th 2017 43
Some Pictures from Hack.IAA
Tue, Sep 19th 2017 96
My Favorite Tech Talks for Developers
Mon, Sep 18th 2017 131
Running Cloud-Native Applications On-Premises
Mon, Sep 18th 2017 77
Node-RED Samples for IBM Watson IoT Hackathon
Mon, Sep 11th 2017 17
Top 10
My Favorite Tech Talks for Developers
Mon, Sep 18th 2017 131
Some Pictures from Hack.IAA
Tue, Sep 19th 2017 96
Running Cloud-Native Applications On-Premises
Mon, Sep 18th 2017 77
Deploying MicroProfile based Apps to IBM Cloud private
Thu, Sep 21st 2017 45
Watson Machine Learning Sample Walkthrough
Tue, Sep 19th 2017 43
Deploying Angular 2 Apps to Bluemix
Tue, Apr 11th 2017 24
Node-RED Samples for IBM Watson IoT Hackathon
Mon, Sep 11th 2017 17
Building Slack Bots with IBM Watson Conversation
Mon, Jun 26th 2017 13
Building Alexa Skills with IBM Watson and OpenWhisk
Thu, Jun 29th 2017 13
Simple Sample of the Watson Document Conversion Service
Wed, Jan 27th 2016 11


Angular Form Validations with Redux for multiple Routes
Twitter Google+ Facebook LinkedIn Addthis Email Gmail Flipboard Reddit Tumblr WhatsApp StumbleUpon Yammer Evernote Delicious
Niklas Heidloff    

Many frontend applications require the extensive use of forms to allow users entering information. Angular supports various mechanisms to handle forms, but I’ve struggled to figure out how to handle validations of data on different pages/routes. Below is a pattern I’ve used based on Redux which doesn’t leverage much of the Angular forms functionality but works very nicely for me.

Initially I thought that my requirements would be pretty straight forward and common for single-page applications. However there were two things which I didn’t manage to address with core Angular forms functionality.

  • Display validation errors for multiple forms on different pages (pages from an user experience perspective; technically routes) including for forms that are not currently visible. In my case I had a sidebar component with validation errors which was displayed on every page.
  • Display validation errors for forms that have not been loaded yet. This was necessary since I read an initial set of data which was used to pre-populate forms.

Angular supports two types of forms handling – template driven forms and reactive forms. Since the reactive forms provide more flexibility I started to use them. My hope was to somehow utilize the router to load all pages without showing them to trigger the out of the box form validations. Unfortunately I didn’t get this to work without a lot of flickering and weird behavior in the user interface.

A separate issue I had was refreshing of components. Read my older blog entry My Advice: Don’t use Angular 2+ without Redux for details. Because of the refresh issues and the form validation issues I decided to do a bigger refactoring of my code to use Redux.

I have open sourced an application which demonstrates how Redux helps to validate data for forms before forms have been loaded. The following screenshot shows an validation error of the password field and in the right column the Redux Chrome extension which displays state information.

angular-redux-forms

Here is an overview of how this has been implemented. Let’s start with the HTML for the password field.

<input [value]="watsonPassword$ | async" (blur)="onBlurWatsonPassword($event)" (keyup)="onKeyUpWatsonPassword($event)" class="form-control" id="watsonPassword" />
<div *ngIf="(validationErrorsPassword$ | async)?.length > 0" class="alert alert-warning">
    {{ (validationErrorsPassword$ | async)[0].displayText }}
</div>

In the component’s Typescript file observables are used for the value of the password field and the validation errors. With the “xxx$ | async” notation above the values are displayed in the user interface when they change.

@select(['tool', 'watsonPassword']) watsonPassword$: Observable<boolean>;
validationErrorsPassword$: Observable<ValidationError[]>;

ngOnInit(): void {
   this.skillOverviewForm = this.formBuilder.group({});
   ...
   this.validationErrorsPassword$ = this.ngRedux.select((state) => {
      let errors: ValidationError[] = [];
      state.tool.validationErrors.forEach((validationError) => {
         if (validationError.itemName == 'watsonPassword') errors.push(validationError);
      });
      return errors;
   });
   ...	
}

onKeyUpWatsonPassword(event) {
   let value: string;
   let element: any;
   element = document.getElementById('watsonPassword');
   if (element) {
      value = element.value;
      this.ngRedux.dispatch({ type: ToolAction.SET_WATSON_USER_PASSWORD, payload: value });
   }
}

When users change the password the Redux reducer is invoked which sets the new value in the Redux store and triggers the validation logic.

export function toolReducer(state: Tool = INITIAL_TOOL_STATE, action: any) {
   ...
   switch (action.type) {
      case ToolAction.SET_WATSON_USER_PASSWORD:
         newTool.watsonPassword = action.payload;            
         Validations.validate(newTool);
         return newTool;     
      ... 
      default:
         return state;
    }
}

In the Validations class all errors are initially deleted and (re-)created if necessary.

export class Validations {
   static validate(tool: Tool) {
      tool.validationErrors = [];
      Validations.watsonPassword(tool);
      ...
   }

   static watsonPassword(tool: Tool): void {
      let itemName: string = 'watsonPassword';
      let error: ValidationError;
      let value: string = "";
      let validatorOutput: boolean;
      let type: string;
      if (tool.watsonPassword) {
         value = tool.watsonPassword;
      }

      validatorOutput = Validators.required(value);
      type = Validators.errorTypeRequired;
      if (validatorOutput) {
         error = new ValidationError(itemName, 'The Watson Conversation password is required.');
         tool.validationErrors.push(error);
      }
      ...
   }
}

Check out the full sample application Conversation Inspector for IBM Watson for details.

The post Angular Form Validations with Redux for multiple Routes appeared first on Niklas Heidloff.



---------------------
http://heidloff.net/article/angular-2-form-redux-multiple-routes
Aug 01, 2017
9 hits



Recent Blog Posts
3
Deploying MicroProfile based Java Applications to Bluemix
Fri, Sep 22nd 2017 2:50p   Niklas Heidloff
Eclipse MicroProfile is an open source project to optimize Enterprise Java for microservices architectures. MicroProfile based applications can be deployed to Kubernetes. This article describes how to build microservices via the Microservice Builder and how to deploy them to Bluemix. The Microservice Builder provides functionality to easily create new Java based microservices. Below is a quick walkthrough how to create new microservices, how to run them locally and how to deploy them to Kubernet
45
Deploying MicroProfile based Apps to IBM Cloud private
Thu, Sep 21st 2017 2:30p   Niklas Heidloff
Eclipse MicroProfile is an open source project to optimize Enterprise Java for microservices architectures. MicroProfile based applications can be deployed to Kubernetes. This article describes how to deploy a sample application to IBM Cloud private. IBM Cloud private is a Kubernetes based platform to run cloud-native applications on-premises. It also comes with a Docker image registry. For developers there is a community edition available to run everything in one virtual machine. The example I&
43
Watson Machine Learning Sample Walkthrough
Tue, Sep 19th 2017 3:37p   Niklas Heidloff
Last month IBM announced the general availability of Watson Machine Learning which can be used by data scientists to create models and it can be used by developers to run predictions from their applications. Below is a simple sample walkthrough. As sample scenario I’ve chosen the Titanic dataset to predict whether people would have survived based on their age, ticket class, sex and number of siblings and spouses aboard the Titanic. I picked this dataset because it seems to be used a lot in
96
Some Pictures from Hack.IAA
Tue, Sep 19th 2017 7:34a   Niklas Heidloff
Last week I attended Hack.IAA, a hackathon with a focus on Artifical Intelligence and Car-2-X Communication organized by DigitalLife@Daimler. 60 students had 24 hours to come up with new business models and innovative solutions. IBM provided access to the IBM Cloud and Watson and helped participants with technical questions. I had great discussions with the students and enjoyed the event. The students used some of the Watson services like Visual Recognition and Conversation, technologies like No
131
My Favorite Tech Talks for Developers
Mon, Sep 18th 2017 3:21p   Niklas Heidloff
During my workouts I enjoy watching tech talks to learn about new technologies and trends. I’ve created a YouTube playlist with some of my favorite tech talks. The videos in the playlist are awesome sessions from great speakers like Martin Fowler, Brian Will, Erik Dörnenburg, Kevlin Henney and Jonas Bonér. The sessions cover topics like cloud-native, microservices, functional programming, reactive programming, engineering culture, coding best practises and more. The post My Favorite Tec
77
Running Cloud-Native Applications On-Premises
Mon, Sep 18th 2017 2:30p   Niklas Heidloff
Cloud-native applications have a lot of advantages compared to monolithic architectures such as scalability and elasticity. Cloud-native platforms typically also provide services that developers can use without having to worry about infrastructure. These advantages are available in public clouds and now also in some private clouds which is important for companies with high data security and privacy requirements. Recently IBM announced IBM Cloud private. The wiki describes the key features: IBM C
17
Node-RED Samples for IBM Watson IoT Hackathon
Mon, Sep 11th 2017 11:49a   Niklas Heidloff
Recently I gave an one hour webinar to help developers to prepare for a hackathon related to IBM Watson IoT. I demonstrated Node-RED and coded live some sample flows. Get the sample flows from GitHub. Functionality: Getting started with the Watson IoT Quickstart Using the IoT Starter Building simple web user interfaces via the Node-RED Dashboard Invoking REST APIs and implementing REST APIs Leveraging Watson services: Conversation, Translation, Tone Analyzer, Text to Speech Here is a screensho
5
Securing Kubernetes Applications with Vulnerability Advisor
Tue, Sep 5th 2017 7:58a   Niklas Heidloff
The Bluemix Vulnerability Advisor checks the security status of container images before deployments as well as the status of running containers. For example it can detect weak passwords, whether SSH is installed or whether images have known vulnerabilities. The Vulnerability Advisor leverages various sources like the CentOS announce archives and Red Hat RHSA announce archives to know about vulnerabilities and it calculates risk based on the IBM X-Force Exchange technology. While this functional
6
Tool to manage all Bluemix CLIs
Fri, Sep 1st 2017 7:33a   Niklas Heidloff
As a Bluemix developer you typically need to use several CLIs (command line interfaces). There is a specific CLI for Bluemix with multiple plugins to manage Bluemix applications and services. Additionally you can use third party CLIs like Docker, Kubernetes and Cloud Foundry against Bluemix. Recently a new tool has been published for macOS ‘IBM Cloud Application Tools 2‘ (beta). I find this tool pretty useful since you can install and update all CLIs with a few clicks. In the past I
4
Introducing the Conversation Optimizer for IBM Watson
Tue, Aug 29th 2017 8:18a   Niklas Heidloff
In order to develop conversational experiences it’s important to understand how users are actually using bots. Based on this data conversational experiences can continuously be improved. Watson Conversation comes with an improve component which helps analyzing and improving bots. Dependent on the service plan all conversations from the last 7, 30 or 90 days are stored. Via the Watson Conversation web interface you can get an overview of the interactions between users and bots, for example




Created and Maintained by Yancy Lent - About - Planet Lotus Blog - Advertising - Mobile Edition