To request an access token using this grant type, the client must have already obtained the Authorization Code from the authorization server. An Authorization Code is a short-lived token issued to the client application by the authorization server upon successful authentication/authorization of an end-user (resource owner). The client application then uses the authorization code to request an access token from the authorization server.

HTTP Method

URL

Sample Request

The examples below shows token requests in an LDAP scenario, with several different grant types.

Request URL

https://{oauth-provider-url}/oauth/oauth20/token

Sample request headers

Note: In the sample request headers below, the Authorization header consist of the clientâs Basic authentication header, as explained in HTTP Basic Authentication. This is one way of sending the authorization credentials. As an alternative, you can send this information in the POST body or, if you are using the GET operation, in the request parameters. For more information, see OAuth: Client Authentication with the Platform’s OAuth Provider.

In the sample request body shown below, the client ID and client secret are included. When the Authorization header is included with the request message, as shown above, you don’t need to send the client ID and client secret in the parameters. Send them either in the header or in the parameters. The below is an example of sending these values in the POST request body if the Authorization header was not sent. Line breaks have been added for display purposes.

The best way to enable the production mode for an Angular 2 application, is to use angular-cli and build the application with ng build -prod. This will build the application with production profile. Using angular-cli has the benefit of being able to use development mode using ng serve or ng build while developing without altering the code all the time.

Interpolation: One-way data binding from the component to the template. Let’s you display information from the component into the template. Example: {{person.name}}.

Property bindings: One-way data bindings from the component to the template. Let you bind data from the component into the template. You typically use them to bind component data to DOM element properties (like for instance the src property of an image). Example: <img [src]="person.imageUrl">.

Event bindings: One-way data bindings from the template to the component. Let’s you bind template events to the component. You typically use them to execute arbitrary code as a response to an interaction between the user and the user interface of your application. Example (click)="selectPerson(person)".

[(ngModel)]: Two-way data binding from the component to the template and vice versa. It syncs data both ways from the component to the template and back. You typically use it within form inputs. Example [(ngModel)]="person.name"

UPDATE (18th May 2017): This tutorial has been updated to the latest version of Angular (Angular 4). Note that the Angular team has re-branded the terms Angular 2 to Angular and Angular 1.x to AngularJS which are now the official names of these frameworks.

The Code Samples

Our Application Up Until Now

At this point in time we have developed a tiny Angular 2 application to learn more about people from the StarWars universe. We have two components, the PeopleListComponent that displays a list of people and the PersonDetailsComponent that displays more information about the character that you have selected.

We use Angular 2 routing to navigate between these two views, the list of people being our default view and the one that is rendered as soon as the application starts.

We Want to Save Our Own Data!

Up until now we’ve just been reading information and we are tired of that! We want to be able to write and save our own data.

In order to do that we are going to transform our PersonDetailsComponent into a form and add some validation on top to ensure that the information that we save is correct.

At the end of exercise, our details form should look something like this:

First Things First! We Need to Add The Forms Module to Our App!

From RC5 onwards we need to declare our module dependencies in NgModule and since we want to use the new forms API you’ll need to import it in our app.module.ts:

Using a File Template Instead of an Inline Template

The first thing we’re going to do now that things are getting serious is to extract our PersonDetailsComponent template in its very own file. Yes you can do that!

As a starting point, I thought it was nice for you to see your template bindings beside your component API but now that we are going to be writing more HTML it is nice to have it separated in its own file and get syntax highlighting and better text editor support altogether (although depending on the editor you’re using you may get great HTML support in your TypeScript via this or this in the future).

How can we use a file template instead of an inline one?

The @Component decorator has a templateUrl property in addition to the template property that we’ve been using thus far. Taking advantage of that property we can tell Angular 2 about which HTML template we want to use with a particular component. Let’s extract our PersonDetailsComponent template into a person-details.component.html file:

A Basic Form in Angular 2

Ok, now that we got that covered, let’s add an HTML form to our view. Angular 2 works perfectly with HTML5 standards so we are just going to create a vanilla HTML form to edit the properties that we have in our Person interface.

Where we use a [value] property binding to bind the component’s person.name property to the input element, and we use the (change) event binding to update our person’s name.

There’s something weird though in this particular example, and that’s the #name right there inside our input element. That’s what Angular 2 calls a template local variable and it’s often used to keep DOM element related references and logic out of our component code.

This feels like way too much work to bind a property from our component to our template and back, doesn’t it?… If only there was a better way… 🙂

ngModel and Angular 2 Two-Way Data Binding

Well there is! The ngModel data binding, very similar to AngularJS ng-model, let’s us establish a two-way data binding for a given property between the component and the template. A two-way data binding effectively syncs the value of a property between template and component forwarding changes in both directions.

The syntax is a little bit special and takes a little bit to get accustomed to:

Hell yeah! You read it right: [(ngModel)]="person.name". Before you start cursing let’s spend a minute longer contemplating this piece of code…

We’ve learned that event bindings are one-directional bindings that go from the template to the underlying component and are represented in brackets (click). We’ve also learned that property bindings are one-directional bindings that go from the component to the template and are represented in square brackets [src]. Therefore if we want a two-way binding, we have something equivalent to an event binding plus a property binding, merge both syntaxes and you get the “banana-in-a-box” syntax of [(ngModel)]. Makes sense right?

The [(ngModel)] two-way data binding can indeed be decomposed into an event/property binding combo like this:

If you run the application in your browser (remember ng serve --open or ng s -o if you’re cool) you’ll be able to see how whenever you change the value in these inputs the changes are reflected instantly in the description.

A Review of Angular 2 Data Bindings

With the [(ngModel)] binding we have now covered all data bindings available to you in Angular 2. Let’s make a quick recap of them before we continue with forms and validation.

Angular 2 has support for these data-bindings:

Interpolation: One-way data binding from the component to the template. Let’s you display information from the component into the template. Example: {{person.name}}.

Property bindings: One-way data bindings from the component to the template. Let you bind data from the component into the template. You typically use them to bind component data to DOM element properties (like for instance the src property of an image). Example: <img [src]="person.imageUrl">.

Event bindings: One-way data bindings from the template to the component. Let’s you bind template events to the component. You typically use them to execute arbitrary code as a response to an interaction between the user and the user interface of your application. Example (click)="selectPerson(person)".

[(ngModel)]: Two-way data binding from the component to the template and vice versa. It syncs data both ways from the component to the template and back. You typically use it within form inputs. Example [(ngModel)]="person.name".

Adding Validation to Our Form

Now that we have a way to update a person’s details let’s add some validation to ensure that the data we’re introducting is legit before we save it. We are going to do the following:

Make the name field required,

Display a super helpful validation error message to the user whenever the field is empty

Enable/disable the form submit button based on the validity of the inputs within the form

The way we track changes and the validity of an input in Angular 2 is through the same ngModel directive that we use for two-way data binding. By using this directive with an input we can obtain information about whether or not the user has done something with the input, wether or not the value has changed and even if it is invalid.

Let’s add the required attribute to the name input to mark it as a required bit of information (One can’t live without a name):

Angular 2 uses the name attribute (in this case name="name") to identify this particular input and keep track of its changes and validity.

Angular 2 Supports HTML5 validation Constraints By Default!

Out of the box Angular 2 will support many of the HTML5 validation constraints like required, pattern, minlengthand maxlength. Outside of that you’ll need to create your own custom validators to extend Angular’s validator system.

We’ll take a look at how you can create your very own custom validators later in this article.

The easiest way to visualize how Angular 2 tracks changes in our input is to see how it adds/removes css classes to the input based on it’s state.

If we update the input with the following snippet of code to display the DOM className property after the input and go to the browser, you’ll be able to appreciate how as you interact with the input different classes are added:

This css file is linked within index.html. As such it represents the global styles for our application which are applied globally regardless of in which component you are in.

In the future you’ll learn that you can define component-level styles that are only applied within a component. Yey!

Back to the PersonDetailsComponent template we now want to display an error message whenever the user doesn’t type the required name. We can do that by creating a local template variablename and setting its value to ngModel. How can we do that?Although unintuitive, you do that by assigning the local template variable to ngModel like this. Update the previous snippet to the following:

You can think of it as a way to gain access to the directive that tracks the changes and validity of the input. Now that name holds the value of the ngModel directive, we can access its properties and find whether or not the input is in a valid state. We can use that information to toggle the visibility of an error message:

<labelfor="name">Name: </label><inputtype="text"name="name"required[(ngModel)]="person.name"#name="ngModel"><div[hidden]="name.valid||name.pristine"class="error"> Name is required my good sir/lady!
</div>

That we will style with this magic css:

.error{padding:12px;background-color:rgba(255,0,0,0.2);color:red;}

Notice how using the property binding syntax we can bind any expression to the [hidden] DOM property. In this case we only hide the message when ngModel tells us that the input is valid or pristine (no reason to show the error if the user hasn’t even started editing the input).

Custom Validation FTW!

Let’s do another example of validation. This time for the input element tied to a person’s weight using the max and min HTML5 input attributes. Let’s say that our Star Wars figures shouldn’t weight less than a feather nor more than a Rancor. We’ll update our template as follows:

<div*ngIf="weight.errors && (weight.dirty || weight.touched)"class="error"><p[hidden]="!weight.errors.min"> Weight must be higher than a feather's. {{weight.value}} is way too low.
</p><p[hidden]="!name.errors.max"> Weight can't be higher than a Rancor's. {{weight.value}} is too high
</p></div>

If you run the example again (remember ng serve --open) you’ll be able to verify that this new validation doesn’t work! Oh no! What do we do?

Angular 2 let’s you extend the built-in validation system with new validators of your own. Let’s create two new validators for the minand max attributes. The validators will be represented as directives which we can create with the aid of our mighty companion: The Angular CLI. You can think of a directive as a way to add custom behavior to DOM elements matching a specific selector.

Type the following:

PS>nggeneratedirectivemin-validator# ng g d min-validator

This will create a new directive for us and register the directive into our AppModule. The new directive will look like this:

In order to turn this new directive into a validator we need to implement the Validator interface which contains the validatemethod. This method will contain the validation logic that will compare the current value of the input with our attribute min value.

But before we can implement that logic we need to get a hold of the min value. We’ll do that taking advantage of the @Input decorator (if you missed previous articles in the series, you can use inputs to pass data into a component or directive) :

exportclassMinValidatorDirective{// new @Input here// it will get the min number from the attribute// For example 5 for <input min=5 ...@Input()min:number;constructor(){}}

And now we implement the Validator interface with the validatemethod as follows:

import{Validator,AbstractControl,ValidationErrors}from'@angular/forms';@Directive({...})exportclassMinValidatorDirectiveimplementsValidator{// new @Input here// it will get the min number from the attribute// For example 5 for <input min=5 ...@Input()min:number;constructor(){}// Define validation logicvalidate(control:AbstractControl):ValidationErrors{constcurrentValue=control.value;constisValid=currentValue>=this.min;// return errors as an objectreturnisValid?null:{min:{valid:false}};}}

Ok! So now we have a custom validator directive for the minattribute ready to go. We have created the directive, tied it to the minattribute via the [min] selector, implemented the validation logic via the Validator interface, registered the directive into our AppModuleso we can use it within our application but there’s one little thing that remains. We need to make Angular Validation’s system aware of this validator. We do this by registering the validator as a provider for the NG_VALIDATORS token inside the @Directive decorator metadata:

Now when the Angular validation system uses dependency injection to get a hold of all the available validators (represented by NG_VALIDATORS) in addition to the built-in validators it will also have access to this new custom validator.

You can now verify that the validation logic we wrote earlier for our weight input is now working. Test to write a weight of -100 and you’ll be greeted by an error message. Yippi!

Now we can repeat the steps for the max validator. Let’s be cool and do the shorthand with the Angular CLI:

PS>nggdmax-validator

And write the validator logic:

import{Directive,Input}from'@angular/core';import{Validator,AbstractControl,ValidationErrors,NG_VALIDATORS}from'@angular/forms';@Directive({selector:'[max]',// register validator in DIproviders:[{provide:NG_VALIDATORS,useExisting:MaxValidatorDirective,multi:true}]})exportclassMaxValidatorDirectiveimplementsValidator{@Input()max:number;validate(control:AbstractControl):ValidationErrors{constcurrentValue=control.value;constisValid=currentValue<=this.max;// return errors as an objectreturnisValid?null:{max:{valid:false}};}constructor(){}}

Tada! Now we have our very own custom validators for min and max, Great job!

Submitting Our Form

Ok! Let’s do a quick summary! Up to this point we have added some validation to the name input within our form so that if the user removes the name we will show an error because you are not supposed to do that with a required field. We’ve also added min and max validation to our weight attribute and some basic styles.

The next step is to actually try to save these changes. To that end, we are going to add a submit button inside our form:

And we need to disable it when the form is invalid so that the user can’t save corrupted/invalid data, cause chaos, mayhem and destroy our beloved servers (although you and I know that you must have this type of validation in your service layer as well as in your client).

In order to do that we create yet another local template variable#personForm to get access to the actual form via the ngFormdirective. We then use that variable to disable the button when the form is invalid:

And now if you test everything that you’ve just done in the browser: Click on Luke Skywalker, change his name to Luke Vader (moahahaha), then save, you should be able to see your changes in an alert box.

Let’s update our component further so we can save this information with the help of our PeopleService.

Saving Information

This has nothing to do with forms and validation so I’ll just run wild like the wind over it without much detail. We are going to add a savemethod in our service and then we are going to save the changes we’ve done on a person in memory within our service.

If you are a very observant person you’ll see that I have added the clone method to this service. The purpose of this mighty teeny tiny method is to avoid sharing the same object references between the different components in the app so that we can simulate “saving” in a way more faithful to reality.

What’s With NgModel and NgForm?

If you are a little bit like me, you are probably slightly confused with the ngModel and ngForm directives. So let’s do some recap about them:

ngModel

ngModel lets you track the state and validity of your inputs

ngModel adds css classes to your inputs based on their state, whether they have been touched, changed or whether they are valid or not.

Using #name="ngModel" in an input element creates a local template variable called #name and assigns the ngModeldirective to it. You can then use the variable to access the ngModel directive properties like valid, pristine, touched, etc.

ngForm

Angular 2 attaches an NgForm directive to every form element.

The ngForm directive exposes the form.valid property that let’s you know if all controls within a given form are in a valid state.

ngModel and ngForm

Whenever you add the ngModel directive to an input Angular 2 is going to register it using that name that you provide (remember name="name") with an NgForm directive that Angular 2 automagically attaches to any form element.

The ngForm directive contains a collection of the controls created using the ngModel directive.

Bonus Exercise. Adding a Select Input in Angular 2

As a bonus exercise let’s try to add a select input with Angular 2 to select the profession of our Star Wars figures. An HTML5 selectelement, also known as dropdown or listbox in UI circles typically has a select element that wraps a collection of option elements.

We will start by adding a profession to the Person interface:

exportinterfacePerson{id:number;name:string;height:number;weight:number;// it is optional because I know it// doesn't exist in the API that we will// consume in the next exercise :)profession?:string;}

Then we update our PersonDetailsComponent to include all the available professions: