Template-Driven Forms in Angular

Forms are the main building block of any application. We use forms for logins, registration, submitting help requests. So, whatever form we are developing must be user-friendly. For example, when something goes wrong, it should have an indication as to why, etc.
Coming to Angular Forms, Angular provides two approaches for developing forms which are Template Driven and Reactive. Let’s try to explore the template-driven approach in this article

Link: https://dzone.com/articles/template-driven-forms-in-angular?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Angular 2 Components and Providers: Classes, Factories & Values

In a previous article, we looked at how to get data into and out of components using the @Input and @Output annotations. In this article, we’ll look at another fundamental aspect of Angular 2 components — their ability to use “providers.”
You may have seen “providers” in a list of properties you can use to configure components, and you might have realized that they allow you to define a set of injectable objects that will be available to the component. That’s nice, but it of course begs the question, “what is a provider?”
Answering that question gets us into an involved discussion of Angular 2’s Dependency Injection (DI) system. We may specifically cover DI in a future blog post, but it’s well covered in a series of articles by Pascal Precht, beginning with: http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html. We’ll assume you are familiar with DI and Angular 2’s DI system in general, as covered in Pascal’s article, but in brief the DI system is responsible for:

Registering a class, function or value. These items, in the context of dependency injection, are called “providers” because they result in something. For example, a class is used to provide or result in an instance. (See below for more details on provider types.)
Resolving dependencies between providers — for example, if one provider requires another provider.
Making the provider’s result available in code when we ask for it. This process of making the provider result available to a block of code is called “injecting it.” The code that injects the provider results is, logically enough, called an “injector.”
Maintaining a hierarchy of injectors so that if a component asks for a provider result from a provider not available in its injector, DI searches up the hierarchy of injectors.

In the previous article, we included a diagram showing that components form a hierarchy beginning with a root component. Let’s add to that diagram to include the injectors and the resources (providers) they register:

Figure 1: Each component has its own injector that registers providers. Injectors create child injectors and a request for a provider starts with the local injector and searches up the injector hierarchy.
We can see from the above that while components form a downwards directed graph, their associated injectors have a two-way relationship: parent injectors create children (downwards) and when a provider is requested, Angular 2 searches the parent injector (upwards) if it can’t find the requested provider in the component’s own injector. This means that a provider with the same identifier at a lower level will shadow (hide) the same-named provider at a higher level.
What are Providers?
So, what are these “providers” that the injectors are registering at each level? Actually, it’s simple: a provider is a resource or JavaScript “thing” that Angular uses to provide (result in, generate) something we want to use:

A class provider generates/provides an instance of the class.
A factory provider generates/provides whatever returns when you run a specified function.
A value provider doesn’t need to take an action to provide the result like the previous two, it just returns its value.

Unfortunately, the term “provider” is sometimes used to mean both the class, function or value and the thing that results from the provider — a class instance, the function’s return value or the returned value.
Let’s see how we can add a provider to a component by creating a class provider using MyClass, a simple class that will generate the instance we want to use in our application.

Figure 2: A simple class with four properties. (Code screenshots are from Visual Studio Code)
Okay, that’s the class. Now let’s instruct Angular to use it to register a class provider so we can ask the dependency injection system to give us an instance to use in our code. We’ll create a component, ProvDemo_01.ts, that will serve as the root component for our application. We load this component and kick-off our application in the bootstrap.ts:

Figure 3: Our application’s bootstrap.ts file that instantiates the root component.
If the above doesn’t make sense, then take a look at our earlier post that walks through building a simple Angular 2 application. Our root component is called ProvDemo, and the repository contains several numbers versions of it. You can change the version that’s displayed by updating the line that imports ProvDemo above. Our first version of the root component looks like this:

Figure 4: CompDemo with MyClass imported, added to the providers array and used as a Type in the constructor arguments.
Adding the MyClass provider to this component is straightforward:

Import MyClass
Add it to the @Component providers property
Add an argument of type “MyClass” to the constructor.

Under the covers, when Angular instantiates the component, the DI system creates an injector for the component which registers the MyClass provider. Angular then sees the MyClass type specified in the constructor’s argument list and looks up the newly registered MyClass provider and uses it to generate an instance which it assigns to “myClass” (initial small “m”).
The process of looking up the MyClass provider and generating an instance to assign to “myClass” is all Angular. It takes advantage of the TypeScript syntax to know what type to search for but Angular’s injector does the work of looking up and returning the MyClass instance.
Given the above, you might conclude that Angular takes the list of classes in the “providers” array and creates a simple registry used to retrieve the class. But there’s a slight twist to make things more flexible. A key reason why a “twist” is needed is to help us write unit tests for our components that have providers we don’t want to use in the testing environment. In the case of MyClass, there isn’t much reason not to use the real thing, but if MyClass made a call to a server to retrieve data, we might not want to or be able to do that in the test environment. To get around this, we need to be able to substitute within ProvDemo a mock MyClass that doesn’t make the server call.
How do we make the substitution? Do we go through all our code and change every MyClass reference to MyClassMock? That’s not efficient and is a poor pattern for writing tests.
We need to swap out the provider implementation without changing our ProvDemo component code. To make this possible, when Angular registers a provider it sets up a map to associate a key (called a “token”) with the actual provider. In our example above, the token and the provider are the same thing: MyClass. Adding MyClass to the providers property in the @Component decorator is shorthand for:
providers: [ provide(MyClass, {useClass: MyClass} ]

This says “register a provider using ‘MyClass’ as the token (key) to find the provider and set the provider to MyClass so when we request the provider, the dependency injection system returns a MyClass instance.” Most of us are used to thinking of keys as being either numbers or strings. But in this case the token (key) is the class itself. We could have also registered the provider using a string for the token as follows:
providers: [ provide(“aStringNameForMyClass”, {useClass: MyClass} ]

So, how does this help us with testing? It means in the test environment we can override the provider registration, effectively doing:
provide(MyClass, {useClass: MyClassMock})

This associates the token (key) MyClass with the class provider MyClassMock. When our code asked the DI system to inject MyClass in testing, we get an instance of MyClassMock which can fake the data call. The net effect is that all our code remains the same and we don’t have to worry about whether the unit test will make a call to a server that might not exist in the test environment.
Continue reading %Angular 2 Components and Providers: Classes, Factories & Values%

Link: https://www.sitepoint.com/angular-2-components-providers-classes-factories-values/

Angular 2 Components: Inputs and Outputs

In this article, we’ll take a look a bit closer at Angular 2 components — how they’re defined, and how to get data into them and back out of them.
This is the second part in the Angular 2 series. You can read part one here. We covered the basic idea of components and decorators in an earlier article, and have specifically seen the @Component and @View decorators used to build an Angular application. This article dives in a bit deeper. However, we can’t cover everything about components in a single article, so future articles will take up other aspects of Angular components.
The code for this article and the other articles in the series is available as in the angular2-samples repo. You can also see the samples running at: http://angular2-samples.azurewebsites.net/.
Although it’s possible to write Angular 2 applications in ECMAScript 5 (the most common version of JavaScript supported by browsers), we prefer to write in TypeScript. Angular 2 itself is written in TypeScript and it helps us at development time and includes features that make it easier for us to define Angular components.
In particular, TypeScript supports decorators (sometimes referred to as “annotations”) which are used to declaratively add to or change an existing “thing”. For example, class decorators can add metadata to the class’s constructor function or even alter how the class behaves. For more information on decorators and the types of things you can do with them, see the proposal for JavaScript decorators. Angular 2 includes several decorators.
As we’ve covered in an earlier article, components are the key building block for Angular applications. They include a view, defined with HTML and CSS, and an associated controller that implements functionality needed by the view. The controller has three major responsibilities:

Manage the model, i.e. the application data used by the view
Implement methods needed by the view for things like submitting data or hiding/showing sections of the UI
Managing data related to the state of the view, such as which item in a list is currently selected.

Depending on your background, the above list might sound familiar. In fact, the Angular component controller sounds very much like the original definition of a view model as defined by John Gossman in 2005:
The term means “Model of a View”, and can be thought of as abstraction of the view, but it also provides a specialization of the Model that the View can use for data-binding. In this latter role the ViewModel contains data-transformers that convert Model types into View types, and it contains Commands the View can use to interact with the Model. — Source (captured 11/27/2015)
Because components aren’t native JavaScript entities, Angular provides a way to define a component by pairing a constructor function with a view. You do this by defining a constructor function (in TypeScript it’s defined as a class) and using a decorator to associate your view with the constructor. The decorator can also set various configuration parameters for the component. This magic is accomplished using the @Component decorator we saw in the first article in this series.
Component Hierarchy
The above describes an individual component, but Angular 2 applications are actually made up of a hierarchy of components – they begin with a root component that contains as descendants all the components used in the application. Components are intended to be self-contained because we want to encapsulate our component functions and we don’t want other code to arbitrarily reach into our components to read or change properties. Also, we don’t want our component to affect another component written by someone else. An obvious example is CSS: if we set CSS for one component, we don’t want our CSS to “bleed out” to another components just as we don’t want other CSS to “bleed in” to our component.
At the same time, components do need to exchange data. In Angular 2, a component can receive data from its parent as long as the receiving component has specifically said it’s willing to receive data. Similarly, components can send data to their parents by trigger an event the parent listens for. Let’s look at how the component hierarchy behaves. To begin, we can draw it as follows:

Each box is a component and technically this representation is called “graph” — a data structure consisting of nodes and connecting “edges.” The arrows represent the data flow from one component to another, and we can see that data flows in only one direction — from the top downwards to descendants. Also, note there are no paths that allow you to travel from one node, through other nodes and back to the one where you started. The official name for this kind of data structure is a “directed acyclic graph” — that is, it flows in only one direction and has no circular paths in it.
This kind of structure has some important features: it’s predictable, it’s simple to traverse, and it’s easy to see what’s impacted when a change is made. For Angular’s purposes, when data changes in one node, it’s easy to find the downstream nodes that could be affected.
A simple example of how this might be used is a table with rows containing customers and information about them, in which a table component contains multiple individual row components that represent each customer. The table component could manage a record set containing all the customers and pass the data on an individual customer to each of the row components it contains.
This works fine for simply displaying data, but in the real world data will need to flow the other way — back up the hierarchy — such as when a user edits a row. In that case, the row needs to tell the table component that the data for a row has changed so the change can be sent back to the server. The problem is that, as diagrammed above, data only flows down the hierarchy, not back up. To ensure we maintain the simplicity of one-way data flow down the hierarchy, Angular 2 uses a different mechanism for sending data back up the hierarchy: events.

Now, when a child component takes an action that a parent needs to know about, the child fires an event that’s caught by the parent. The parent can take any action it needs which might include updating data that will, through the usual one-way downwards data flow, update downstream components. By separating the downward flow of data from the upwards flow of data, things are kept simpler and data management performs well.
Continue reading %Angular 2 Components: Inputs and Outputs%

Link: https://www.sitepoint.com/angular-2-components-inputs-outputs/