Integrating Validation in Angular 2 and ASP.NET Core

I’m building an Angular 2 app with an ASP.NET core web API behind it and need to add some validation. Obviously, I need to validate on the server in the web API, but I also want to do some client validation to make sure the user experience is good …

Server Validation

Here’s my model, which you can see is using attributes to define some required field validation:

Here’s our controller below.

If the required fields aren’t filled in (detected from the attribute validation) a HTTP 400 status code is returned with the validation errors in the response body.

We also do some more complex validation, checking if the email address is already in use. Again we return a 400 and the validation error if the email address exists in our database.

So, let’s test our API in Postman.

Test that required fields are validated:

Test that a valid person is saved:

Test that a person with an email address already in the database is validated:

Wiring up our Angular 2 app

Now, that we have our web API in place, let’s build our page to submit a new person.

At this point we’re not going to implement any clientside validation – we’re just going to handle the validation coming from the server.

Here’s our component markup:

  • Lines 1-7 will show the validation errors from the server
  • Lines 8-10 will show confirmation that the person has been saved into the database ok
  • Line 12 defines our form, telling angular that the form object will be called personForm and submit handler will be a function called onSubmit
  • Lines 14-46 define our field inputs for the person
  • Lines 48-52 defines our submit button

Here’s our component code:

  • Line 14 defines a variable called errors which will be an array of validation errors
  • ngOnInit on line 19 creates our form object with no client side validation defined at the moment
  • onSubmit posts the person object to our web API. You can see we catch validation errors on lines 47-55, pushing them to the errors array

If you run the app and hit the Submit button without filling in the inputs, you get something like:

Client Validation

Now, let’s implement the client validation in the angular app.

First, we need to change ngOnInit to include the validation rules:

Then, we need to change our markup for the field inputs to output the validation errors. Here’s the markup for the title input:

  • Line 1 adds the has-error CSS class if we have touched and not filled in the input
  • Lines 13-16 displays the error message beneath the input if we have touched and not filled in the input

So, cool, if the user doesn’t fill in any of the inputs, validation errors will be shown before the submit button is pressed:

However, what if we enter a duplicate email address:

As you can see, the validation error from the server is shown which is good, but ideally we want to highlight the email input and display the error beneath it. So, we need to integrate our validation errors from the server into Angular’s validation.

The solution is in the highlighted lines below. We know the field name from the server’s validation error dictionary. So, if the field is on our form, we flag to angular that there is an error using the control’s setErrors function.

In our example, we don’t have any validation that is not bound to a single field (cross field validation), but if we did, the validation errors would be shown at the top of the page.

Now, if we try to input a duplicate email, our user experience is much nicer:

Recommended reading for learning more about making Angular and ASP.NET core work well together:

Taking Stripe Payments with Angular 2 and ASP.NET Core

Stripe is a service that allows you to very easily take payments online. In this post, I’ll go through how to take a payment via stripe using an Angular 2 frontend and an ASP.NET Core backend.

Sign up to Stripe

Firstly, we need to sign up for a stripe account. You can signup for a free test account here

After you have signed up, we need the Secret and Publishable keys. You can get these from Your account > Account settings > API Keys

Frontend Page

Let’s build the frontend first, using an Angular 2 component.

We are going to use stripe checkout which is super easy to implement and protects us from any PCI headaches (as long as our site runs on HTTPS).

First, we need to add a reference to the standard stripe checkout JavaScript in our server side ASP.NET Core view (line 3). This adds the global variable StripeCheckout which we’ll reference in our angular component. Note that we can not add this script into our angular component template because angular will remove it.

Now let’s add our angular payment component …

Here’s the simple markup (referencing bootstrap classes) which allows a user to buy 3 products, a T-shirt, some trainers or some jeans. Each button will invoke a function in our component code to take the payment via stripe. We show whether the payment has been successful or not in the last div in the markup, referencing a property called takePaymentResult.

Our component code is below …

Our 3 button handlers at are the bottom of the code and simply call into openCheckout() passing the product name, amount (in pence) and a callback to get invoked when we receive a token from stripe.

openCheckout() references the global variable StripeCheckout from checkout.js. Firstly we configure StripeCheckout, passing our publishable key and then we open the stripe payment form passing in our product and amount for the transaction.

After the user enters their credit card details and presses the Pay button, these details will be sent to stripe to initiate the payment. Stripe will then return a token and our callback (takePayment()) will be invoked.

takePayment() will call our ASP.NET Core API (/api/stripepayment) using angular’s http service. This is where the stripe payment will be processed – we’ll implement this in a minute.

The status from the /api/stripepayment API response is put in takePaymentResult which will be presented in the UI by angular.


OK, on to our web API that processes the stripe payment …

First, we need to bring in via nuget – it makes processing the payment very simple.

Below is the full API controller and the API request model, StripePaymentRequest

First we tell stripe our secret key (line 7). We then setup the stripe charge object, setting the token, amount and description (to the product name). We also set our payment reference in the MetaData dictionary so that we tie the payment in our app to the payment in stripe.

The charge is then made and the result (which includes whether the payment has been successful) is passed back down in the response.

Test it!

You can test different scenarios using stripe’s test credit card numbers here.

Recommended reading for learning more about making Angular and ASP.NET core work well together:

Styling components in Angular 2

In my last post I went through creating a few simple components. In this post I’m going to play around with styling in those components …

Adding styles and using ngClass

First, I’m going to change the results so that we see all the customers highlighting the matches. So, it will look something like this …

SearchComponent needs to change to …

  • On line 21 we are now initialising a status property on each customer
  • On Lines 23 to 30 we have an updateCustomers() method which sets the status property on a customer to highlight if matched

ResultsComponent needs to change to …

  • We now have a highlight style name defined on line 10
  • On line 18 we use the ngClass directive to set the class on the span to the customer’s status property


I’m now going to play around to see whether the style leaks out of the component.

First, lets reference the style in the parent component, SearchComponent …

… and we see that the style doesn’t leak up – “Search for a company” doesn’t have a yellow background …

Now let’s add a child component to ResultSubComponent to see if the style leaks down. ResultsComponent is now …

… and the code for ResultSubComponent is …

On line 6 we reference the highlight class.
If we run the app we see that the style doesn’t leak down – “is this text highlighted?” doesn’t have a yellow background.

This is great – generally, this is what we want. However, what if we do want the styles to leak down into sub components? We can make use of the ViewEncapsulation enum on the encapsulation property in the search component …

Line 2 sets the encapsulation to “Native” which means the shadow DOM is used. The result is what we want – the styles leak down into the sub components …

However, although this works in Chrome, it doesn’t work in Firefox, IE or Edge because they don’t support shadow DOM yet.

Here are all the encapsulation modes …

  • None. No encapsulation – the styles will leak up and down
  • Native. Shadow DOM encapsulation – the styles will leak down, but this only works in Chrome at the moment
  • Emulated. The default encapsulation – the styles do not leak out

Recommended reading for building great angular apps:

Connect with me:RSSGitHubTwitterLinkedIn

Building a simple component in Angular 2

A while back, I posted about building a simple component in react. In this post, I’m going to go through building that same component in Angular 2 …

The component will look like below. There will be a parent component with 2 child components …

  • Criteria. The search textbox and “go” button
  • Results. The list of results
  • Search. The overall component – the parent of Criteria and Results

Consuming component

The code of the consuming component is listed below …

  • On line 2, we import the search component which is our top level component
  • On line 6, we declare that we are going to use the search component in the component’s markup
  • Finally on 8, we reference the search component, using it’s tag which will be search

Search component

The code for the search component is listed below …

  • Lines 3 and 4 import the criteria and results components
  • Line 8 declares that the criteria and results components are going to be referenced in the markup
  • Line 11 references the criteria component and calls the handleSearch() function when the critieria’s update event occurs
  • handleSearch() is declared on lines 33 to 37. The implementation finds the customers matching the given criteria and sets the filteredCustomers property
  • Line 12 references the results component and sets its data property to the search component’s filteredCustomers property. The data property will be updated every time the filteredCustomers property is updated automatically by angular

Criteria component

The code for the criteria component is listed below …

  • There is an update custom event declared on line 14. The search component makes use of this to trigger a search
  • Line 8 calls the handleClick() method, passing the value of the criteria, which in turn triggers the update event

Results component

The code for the results component is listed below …

  • On line 17 we have a custom property declared called data which the search component uses to pass in the data
  • Lines 9 to 11 make use of angular’s ngFor to iterate over the data and display the name for each item

That’s it – pretty simple!

Recommended reading for building great angular apps:

Connect with me:RSSGitHubTwitterLinkedIn

Angular 2 Custom Events

In my last post I covered passing data into components via custom properties. In this post I’ll deal with passing data out of components via custom events …

Let’s say we want to implement a component to capture a name, telephone number and email address. Our component code initially looks like this …

However, want to expose a save event so that the consumer of this component can do something with the captured name, telephone number and email address. We want to reference the component like this …

So, we need to expose a custom event called save.
Here’s how we do this …

We declare save as a property in our ContactComponent class on line 16.
We need to prefix the property with the Output annotation. This tells angular that this is a property that can output data. We need to import the Output annotation on line 1.
The type of the property is an EventEmitter. More info on EventEmitter can be found in the angular docs.
On line 21, we trigger the next save event, passing the name, telephone number and email address to the consumer.

So, we can now consume the component as follows …

… which results in the name, telephone number and email address being output to the console when the save button is clicked.

Recommended reading for building great angular apps:

Connect with me:RSSGitHubTwitterLinkedIn

Passing Data to Sub Components in Angular 2

Let’s say we have a list of products we need to display and we want a sub component to be responsible for displaying each product. We want it to look something like this …
sub component

Parent component

So, our parent component is as follows to begin with …

… Line 8 iterates through the products and line 9 is ready to reference a sub component.

Sub component

Our sub component is as follows …

Lines 9 and 11 reference a product object that, at the moment, the sub component isn’t wired up to …

Wiring them up

First we need to reference the sub component from the parent component by adding an import statement …

… and also referencing the selector in the template.

However, we need to pass the product when we call the sub component. First we need to use the Input annotation in the sub component to declare that a property called product can be passed in …

In the parent component, we can then set the product property when we reference the sub component.

That’s it – nice an simple!
Here’s the full listing of the parent and sub components …

Recommended reading for building great angular apps:

Connect with me:RSSGitHubTwitterLinkedIn

Angular 2 Async Validation

I recently posted about Angular 2 Form validation which didn’t cover asynchronous validation. This post does cover an async validation example …

I’ve put all the classes in the same file to make the example simpler to show and read. The example gives a textbox for the user to enter a product code and validates that the product code exists and puts a description at the side if it does.

Referencing an async validator in FormBuilder

The first key point is that you reference the async validator in the 3rd parameter in None async validators go in the 2nd parameter – I only have a async validator in my example.

Writing the async validator

The async validator needs to return a promise that in turn returns null if valid or something else if not valid. In this example, I am calling a ProductService class to check whether the product exists

Here’s the full listing …

Recommended reading for building great angular apps:

Angular 2 Two Way Binding

In my last 2 posts I went through the event binding and property binding syntax in Angular 2. Event binding flows from the component’s template to the model and property binding flows in the opposite direction from the model to the template.

Event and property binding are one-way binding. Two-way binding is where the data flows in both directions between the component’s template and model. Given that event binding uses () syntax and property binding uses [] syntax it makes sense 2 way binding uses [()] syntax!

Angular 2 binding

The ngModel directive allows us to do 2 way data binding. In the following example the criteria component property is bound to the search input’s value in both directions …

Recommended reading for building great angular apps:

Connect with me:RSSGitHubTwitterLinkedIn

Angular 2 Property Binding Syntax

In my last post I went through the event binding syntax in Angular 2. This post details property binding syntax …

Property binding is where data flows from the component’s model into the component’s template to set a DOM property or an angular directive. The basic syntax for property binding is …

… where propertyName is a DOM property name or a directive name and an expression is an angular template expression. An angular template expression is just a JavaScript expression with a few exceptions.

In the example below, the agree checkbox is disabled until a name > 2 characters is entered. The name text box is green when > 2 characters and otherwise red. The submit button is disabled until the agree checkbox is ticked.

There are better ways to acheive this behaviour but the example demonstrates property binding in angular 2.

  • On line 8, validateName() is called as the user enters a name which in tern sets properties validName and nameClass on lines 29 to 37
  • Also on line 8, the ngClass directive is bound to the nameClass property
  • On line 9, the checkbox’s disabled property is bound to the opposite of the validName property
  • Also on line 9, setAgreed() is called when the checkbox is checked / unchecked which in tern sets the agreed property on line 39
  • On line 10, the submit button’s disabled property is bound to the opposite of the agreed property

Recommended reading for building great angular apps:

Connect with me:RSSGitHubTwitterLinkedIn

Angular 2 Event Binding Syntax

Angular 2’s binding syntax is a little strange at first but after a while it does make sense when you get familar with all the different types of bindings.

The basic syntax for event binding is …

… where eventName is a native DOM event and functionToCall is a function in the component’s class. You can pass the native event argument in using $event.

Below is an example of a search input component …

Some key points …

  • On line 6 we bind to the keypress event on the textbox calling the preventNumbers() function. We pass in the native event argument using $event
  • On line 6 we also use a local variable, #criteria, so that we can reference the textbox in the button’s binding on line 7
  • On line 7 we bind to the click event on the button calling the search() function passing in the value of the search textbox.

Recommended reading for building great angular apps:

Connect with me:RSSGitHubTwitterLinkedIn