Compared to Angular 1, Angular 2 offer more choices for working with forms and more control over the data flow between a form and a model. However, I feel that Angular 2 provides form-related APIs and directives that are quirky and confusing, while also increasing the amount of work required to manage simple forms. This article isn’t intended to be a tutorial for working with forms in Angular 2 and some of the code inside is not code you want in a real application. Some of the code only exists to demonstrate how forms work.
I apologize for not taking the time to make this post shorter.
Angular 1 simplified working with forms by providing the ngModel directive. ngModel could synchronize an input’s value with a model property in a JavaScript object using 2-way data binding. ngModel also worked behind the curtains with an ngForm directive to build a data structure representing the state of the form and all the inputs inside the form. The data synchronization and the current form state gave us a straightforward approach to initializing, validating, and receiving form input.
At a high level, Angular 2 offers two different approaches to working with forms. Both approaches can use the new NgModel directive for 2-way data binding, although the new NgModel doesn’t work exactly like the old ngModel of Angular 1.
The first approach we’ll look at is a declarative approach using NgForm and NgModel. We’ll call this approach the NgForm approach, because the form level directive we’ll use is NgForm.
The second approach we’ll look at uses more imperative code and interacts with the form through one or more objects that abstractly represent controls on the page. We’ll call this the NgFormModel approach, because the form level directive we’ll use is named NgFormModel.
Because there is a lot of flexibility in Angular 2, we’ll probably see many different variations of these 2 different approaches to forms. The code in this article is not the only way to work with forms.
As a sample scenario, imagine we want to edit information about a movie. We have a Movie model and a MovieService to translate JSON from the server into the Movie model. Given these pieces, a component to edit a specific movie might have code inside like the following.
movie: Movie; constructor(private movieData: MovieService, private params: RouteParams, private router: Router) { } ngOnInit() { var id = this.params.get("id"); this.movieData.get(id) .subscribe(movie => { this.movie = movie; }); }
The important piece here being that during initialization, the component uses a service to retrieve a movie model and assign the movie to a bindable field named movie. Here’s the essence of a template to edit a movie.
<form> <input type="text" [(ngModel)]="movie.title" required> <!-- other inputs and labels omitted ... --> <input type="submit" value="Save" (click)="save()"> </form>
This simple template will give us 80% of the functionality we need. When the component updates the movie with fresh data from the server, NgModel will push updated values into the form. And, when the user types into the form, NgModel will push the form values back into the movie model. When the user presses submit, the save method only needs to take the existing movie model and ultimately serialize the values into an HTTP POST.
At this point we can even write style rules to highlight elements when they are in an invalid state. Some Angular 2 tutorials imply this is only possible after manually adding an additional directive. However, there is an NgControlStatus directive that automatically attaches to elements using the NgModel directive and modifies the classNames property to indicate when an input is valid, invalid, valid, dirty, pristine, etc. Since we have a required attribute on the input for a movie title, we could turn the entire input red when the input is empty using the following CSS.
.ng-invalid { background: red; }
Angular 1 users will recognize the CSS name ng-invalid. We could use the same style rule with Angular 1. The similarities with Angular 1 mostly end here, however. To achieve the last 20% of the functionality the form requires we need to dive into some additional directives and syntax involving an unhealthy amount of misdirection.
Imagine we want to add a simple validation message that appears when the movie title is empty. In Angular 1 you could name a form and the inputs inside a form and have access to a data structure representing the entire form in the template scope. In Angular 2 there is still an NgForm directive that automatically attaches itself to <form> elements and provides an API to determine if a form is valid or invalid. Unfortunately, the NgModel directive no longer coordinates with NgForm to track the validity of a specific input. This is unfortunate because the NgModel directive knows about the validity of its associated input (NgControlStatus relies on this knowledge). We can see NgModel at work by grabbing a local reference to the NgModel directive inside the template.
<input type="text" required [(ngModel)]="movie.title" #title="ngForm"> <span *ngIf="!title.valid"> Title is required! </span>
In the above code, title becomes a local variable in the template and is assigned a reference to the ngForm directive. There is no actual ngForm directive on the input, however, but the code works because NgModel uses the exportAs property of its directive definition to alias itself as ngForm for these types of expressions. A confusing bit of indirection, I think, but an indirection that at least consistently repeats itself in one other scenario we’ll see later.
Although the above code can help us write validation messages for a specific input, it won’t help us track the validity of the form or the model as a whole. To achieve the holistic view, we need to start working with the real NgForm directive, the one attached to the form element. We’ll also switch to using NgForm’s submit event instead of using a click handler on the submit button.
<form #form="ngForm" (ngSubmit)="save(form)" novalidate> <input type="text" required [(ngModel)]="movie.title" #title="ngForm"> <span *ngIf="!title.valid"> Title is required! </span> <!-- other inputs and labels omitted ... --> <input type="submit" value="Save" /> </form>
With this new code we are now passing a reference to the NgForm directive into the save method of the component. The save method might look like the following.
save(form) { if(form.valid) { this.movieData.save(this.movie) .subscribe(updatedMovie => { this.router.navigate(['Details', {id: updatedMovie.id}]); }); } }
Except … the check for form.valid in the above code won’t work. Again, in Angular 1 the NgModel directive would register itself with its parent NgForm so the form would know about the validity of all the data bound inputs of the form. In Angular 2, NgModel knows if the model is in a valid state, or not, but NgModel doesn’t coordinate with the form directive. In other words, the user could have an empty title input, but the NgForm we are working with will still present itself as valid.
In order to add the input’s state to the form, we need to use a new directive with an alias of NgControl.
<input type="text" required [(ngModel)]="movie.title" ngControl="title"> <span *ngIf="!form.controls.title?.valid"> Title is required! </span>
Now the form will know about the title input and form.valid will include a validity check of the title. We can even dot into the form.controls object to find the title, as demonstrated in the NgIf expression. We can still alias the input to a local variable if the expression is too cumbersome.
<input type="text" required [(ngModel)]="movie.title" ngControl="title" #title="ngForm"> <span *ngIf="!title.valid"> Title is required! </span>
Note that in this case the title variable is not going to get a reference to NgModel, but instead reference the directive put in place by the ngControl attribute (which is the NgControlName directive because this directive, like NgModel, uses exportAs to alias itself as ngForm).
Here then, are some of the facts to know about the current situation.
When I dig into the details like the ones listed above, I have to wonder why NgControlName exists. NgModel could give us the same capabilities without adding an extra directive. I’m biased with the (relative) simplicity of Angular 1, but what’s happening looks like unnecessary complexity.
Perhaps one reason for the complexity of the model approach is that Angular is pushing developers away from using two-way data binding features. I feel this is unfortunate. Two-way binding has gotten a bad reputation because it was easy to abuse in situations where two-way binding isn’t an appropriate solution. For example, updating a model value in one controller of the application and allowing the change to implicitly propagate through other controllers on the screen which in turn could also update the same value. Other UI frameworks provide solutions for these complex UI scenarios using events, messages buses, or event aggregators.
Most forms, on the other hand, are a closed loop. I need to populate the inputs with values, and then retrieve the input values into an object I can serialize and and send off to the server. NgModel was perfect for this scenario where data would only flow between the form and the model. Certainly there are complex forms out there in the world, but I suspect the simple case represents more than 80% of the forms in existence.
For complex forms, Angular 2 provides control and form abstractions that allow explicit data shuffling and validation in code. The template code in this approach is a bit simpler.
<form [ngFormModel]="form" (ngSubmit)="save()"> <input type="text" [ngFormControl]="title"> <span *ngIf="!form.controls.title?.valid"> The title is required! </span> ... <input type="submit" value="Save"> </form>
In the above template, NgFormModel and NgFormControl will bind their respective DOM elements to controls created by the underlying component. In contrast to our previous snippet of component code, the component associated with this template does not contain a field of type Movie. Instead, the component contains fields representing the form and the inputs inside the form.
form: ControlGroup; title: Control; constructor(private movieData: MovieService, private params: RouteParams, private router: Router) { this.title = new Control("initial value", Validators.required); this.form = new ControlGroup({ title: this.title // ... }); }
Notice how validation rules have moved. Instead of being attributes in the template the rules are applied in code. The API here feels a bit clumsy and forces you to compose all rules for a control into a single composite rule using Validators.compose. There are many places in the Angular 2 API where arrays of things are accepted as a parameter, but not here for validation rules.
Also, instead of constructing a ControlGroup directly, the component could inject a FormBuilder and use the builder to create the control group. The API is the same for both, and again a bit clumsy since you pass the grouped controls as key value pairs. I think a reasonable alternative would be to give each individual control a name (which a control should have in any case), and then create a group from a collection of controls.
In theory, creating controls and their associated validation rules inside the component makes unit tests against the component more valuable. We can write asserts to make sure the proper validation rules are in place. In practice I think this is overkill for most simple forms with declarative validations. There is a lot of test code needed to make sure a single required attribute is in place, and it is the type of test that will live in the test mass for years without failing. Certainly complex validation logic needs testing, but perhaps not the application of the logic. If anything, an argument could be made to push complex validations into the model itself instead of coupling the logic with a specific UI component.
Although it is not necessary to create a field for each individual control, doing so allows for cleaner code when you access the control. For example, when data arrives from the server we can use the fields to update the screen.
ngOnInit() { var id = this.params.get("id"); this.movieData.get(id) .subscribe(movie =>{ this.title.updateValue(movie.title); }); }
Here again there is a bit of an oddity in the API. A control has several set methods (setParent, setErrors), but when it comes to the value property, the method to set the value is named updateValue. Yes, I’m picky, but it is often the small inconsistencies that tell the biggest story about an API.
Updating a model or sending the form information back to the server is the above operation in reverse. In other words, you can go to each control and read the value property to receive the associated input value.
If all the code required to update and read the control values is bothersome, you can still use NgModel in combination with NgFormControl, just like NgModel works with NgControlName.
<input type="text" [ngFormControl]="title" [(ngModel)]="movie.title" > <span *ngIf="!form.controls.title?.valid"> The title is required! </span>
Now a component only needs to set a movie field to set the control values, and read the field to fetch the control values.
There are many variations to the different approaches I’ve presented here. The approach you’ll want to use comes down to answering a couple questions. Do you want to avoid using NgModel because two-way binding is evil? If so, use NgFormModel and explicitly read and write control values from the code. Do you want to avoid writing component code for every individual control on the screen? If so, use NgForm and NgControlName to instantiate controls from the template (and synchronize values using NgModel).
Although I might sound critical of the Angular 2 approach to forms, there are some interesting scenarios these approaches enable which I’ve run out of room to cover. For example, treating changes in a form as an observable stream of events. Also, all the APIs and directives provided allow for a tremendous amount of flexibility and cover more application scenarios compared to Angular 1.
Overall though, I worry that all of the similar names (ngControl versus ngFormControl), the similar but different syntaxes (ngControl=”..” versus [ngFormControl]=”..”), and aliasing (NgControlName uses an NgControl selector but exports as ngForm) is too much for busy developers who will cargo cult a solution without understanding the implications. And in the end, there is no simple approach to handle simple forms.
It started, as most endeavors involving Rob do, with a simple email that ends with “I think it will be fun!”.
Fast forward a bit and I’m in the ExCel London being mic’d up by a film crew. Jon is in the room wearing a t-shirt and the mic keeps falling off. Mine keeps folding under my collar, so I’m buttoned up to the top as if I were ready for morning mass. There’s an AV guy in front of us with safecracker headphones trying to eliminate all the hissing and crackling that comes to life in a room full of electrically powered machinery. We’re swapping microphones, changing cables, and positioning laptops. Just as we think we are ready to go – blam! My microphone belt pack falls off my chair. The lapel mic is ripped off my shirt and is tumbling arse over elbow across the floor. Safecracker guy is grimacing and muttering something in polite British. We’ve been at this setup for 30 minutes now and I’m starting to think the show will not go on.
We get setup again, and the recording begins. For the next 75 minutes we are knee deep in C# code, disassemblies, and expression trees. You can watch those 75 minutes in the Pluralsight Play by Play: C# Q & A.
Rob’s always right. It was fun.
The word template in web programming makes one think of a reusable document or string you can combine with model data to produce output. Famous examples include Razor, Jade, and Handlebars. Template literals in JavaScript are not templates in this same sense, which is perhaps why they were originally referred to as quasi-literals in early specification work.
I've seen a number of developers become angry when thinking they can declare a template literal and then reuse the template with different inputs. Note: the following code doesn't work, but represents how one might think template literals should work.
let template = `${x} + ${y} = ${x+y}`; let three = template.format({x:2, y:3}); let ten = template.format({x:5, y:5});
The runtime will evaluate the expressions inside the template immediately. If x and y aren't available when the template is defined, a ReferenceError brings the script to a halt.
The easy solution, like most solutions in JavaScript, is to use a wrapper function.
let template = (x,y) => `${x} + ${y} = ${x+y}`; let four = template(2,2); let eight = template(6,2);
If you'd rather think in terms of model objects instead of individual parameters, add some destructuring to the parameter list.
let template = ({x,y}) => `${x} + ${y} = ${x+y}`; let seven = template({x:4, y:3}); let three = template({x:1, y:2});
Aurelia continues a march towards beta 2 with a big February release. There are no breaking changes, and the framework still provides features to make building applications easy. One feature I’ve used recently is the navigation model provided by the Aurelia router. I think of the navigation model as an amalgamation of routing configuration with current routing state to provide a data source for navigation menus and other UI components.
The routing configuration comes from the conventional configureRouter method of a view model. For top-level routing, the method might look like the following.
configureRouter(config, router) { this.router = router; config.title = "Movies"; config.map([ { route: "", name: 'home', moduleId: "movies/list", title:"List", nav:true, settings: { icon: "home" } }, { route: "about", moduleId: "about/about", title: "About", nav:true }, { route: "details/:id", name:"details", moduleId: "movies/details" }, { route: "edit/:id", name:"edit", moduleId: "movies/edit" }, { route: "create", name:"create", moduleId:"movies/edit" } ]); }
Notice the nav and settings properties in the first RouteConfig entry. The nav property identifies to the router which of the entries are part of the navigation model. The settings property allows us to attach arbitrary data to a RouteConfig entry, data we might find useful when binding to the navigational model in a view. In this example, the setting is the name of a Font Awesome icon. We can use the resulting navigation model in a view like so:
<ul class="nav navbar-nav"> <li repeat.for="row of router.navigation" class="${row.isActive ? 'active' : ''}"> <a href.bind="row.href"> ${row.title} <i if.bind="row.settings.icon" class="fa fa-${row.settings.icon}"></i> </a> </li> </ul>
The navigation model is just one of many features to like about Aurelia.
Six years ago, Mark Seeman authored a post titled “Service Locator is an Anti-Pattern”. All of the problems Mark demonstrated back then are still problems today. I’ve been pointing developers to Mark’s post because the service locator anti-pattern is a pattern I’ve seen creep into some early ASP.NET Core code bases. The code usually looks something like the following:
var provider = HttpContext.ApplicationServices; var someService = provider.GetService(typeof(ISomeService));
It is easy to use the service locator pattern in ASP.NET. Nearly every type of component, from controllers to views, have access to the new HttpContext, and HttpContext exposes a service provider via ApplicationServices and ReqeustServices properties. Even though HttpContext facilitates the service locator pattern, I try to avoid using these properties.
The service locator pattern typically appears in applications that have not fully embraced an inversion of control container, or dependency injection. Yet, the new ASP.NET offers these features from the very beginning of an application, meaning it is just as easy (or easier) to avoid the service locator pattern.
In “How To Stop Worrying About ASP.NET Startup Conventions”, I remarked how the Configure method of the Startup class for an application is an injectable method. The runtime will resolve any services you need from the application container and pass them along as arguments to this method.
public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IAmACustomService customService) { // .... } }
Custom middleware has two opportunities to ask for services. Both the constructor and the conventional Invoke method are injectable.
public class TestMiddleware { public TestMiddleware(RequestDelegate next, IAmACustomService service) { // ... } public async Task Invoke(HttpContext context, IAmACustomService service) { // ... } }
Constructor injection is good for those services you can keep around for the duration of the application, while Invoke injection is useful when you may need the framework to give you a service instance scoped to the current HTTP request.
Constructors are injectable.
public class HelloController : Controller { private readonly IAmACustomService _customService; public HelloController(IAmACustomService customService) { _customService = customService; } public IActionResult Get() { // ... } }
You can also ask for a dependency in a controller action using the [FromServices] attribute on a parameter. Instead of model binding the parameter from the HTTP request environment, the framework will use the container to resolve the parameter.
[HttpGet("[action]")] public IActionResult Index([FromServices] IAmACustomService service) { // ... }
[FromServices] also works on model properties. For example, the following action needs an instance of a TestModel.
public IActionResult Index(TestModel model) { // ... }
The TestModel class class looks like the following.
public class TestModel { public string Name { get; set; } [FromServices] public IAmACustomService CustomService { get; set; } }
For property injection to work, the property does need a public setter. Also, constructor injection does not work for model objects. Both of these facts are lamentable.
In “Extending Razor Views”, I made the argument that the @inject directive should be the only extensibility mechanism you should use.
@inject IAmACustomService CustomService; <div> Blarg </div>
For every other type of component there is almost always a way to have constructor injection work. This is true even for action filters, which have been notoriously difficult in previous versions of ASP.NET MVC. For more on DI with filters specifically, see Filip’s post “Action Filters, Service Filters, and Type Filters”.
After graduate school my first job was programming in assembly language for an 8 bit Hitachi CPU. The software would fire infrared light through organic substances to measure the amount of moisture or protein inside. Even at the low level of opcodes and operands, software (and hardware) still presented auras of mystery for me at this early point in my career. Every day presented a challenge and the opportunity for a thrill when bits aligned well enough to work.
I’ve largely ignored the Raspberry Pi since it first appeared. I bought one 2 years ago to give my youngest son some inspiration to write Python code. The plan worked. But, I’ve never bought one for myself, and assumed a “been there, done that” attitude.
Then one weekend, on a whim, I threw a CanaKit Raspbery Pi 2 kit into my shopping cart. Even though I had been there and I had done that, it was a long time ago. And, those being good times, maybe I could relive them a bit.
Growing up in a county with blue laws, I’m still astonished when a package arrives on a Sunday. Who needs delivery drones when sentient employees of the US Postal Service deliver packages with a smile?
Thanks to the Windows IoT Dashboard, I had the Pi booted into Windows 10 only 20 minutes after receiving the package.
The decision to use Windows 10 was an impulse decision. In hindsight, perhaps not the best decision for what I wanted to do with the Pi. Linux distros on the Pi give a general purpose operating system with the option to apt-get nearly any application, driver, or toolset. Win10 feels like an operating system built for a specific purpose – running Windows Universal application prototypes deployed by Visual Studio. Don’t think of Win10 IoT as Windows on an ARM processor. Win10 IoT has no Cortana, or start menu, or even a shell, for that matter. Although, it does listen for ssh connections out of the box.
Win10 IoT has limited hardware support and does not support the WiFi dongle provided with the CanaKit I bought. I had to plug in an Ethernet cable before I was able to reach the Pi with ssh. Win10 does support a $10 Realtek dongle, which I purchased days later and works well. If I knew before what I know now, I would have checked the hardware compatibility list up front, but my impulse buys rarely exhibit such caution.
You can also connect to Win10’s built-in web site on port 8080. This is the easiest way to configure devices like the WiFi dongle, although you can also run netsh commands through ssh or remote Powershell.
Although running a Windows Universal app was tempting, I wanted to use .NET Core (currently dnx) to get some bits working on the Pi. The setup is remarkably easy. The first step is getting some Core CLR bits onto the development machine.
dnvm install latest -r coreclr -arch ARM -u
The key options here is –arch ARM. Note there is currently an issue here, as dnvm will use the new install to set the process path. Since the path is for an ARM architecture, dnx is unusable until you dnx use a runtime with the appropriate architecture. Then, once you have an application written, be it command like or web application, use dnu (currently) to publish the application, including the runtime.
dnu publish --out "c:\out\HelloPi2" --runtime dnx-coreclr-win-arm.1.0.0-rc2-16357
The above command packages the application, including source and the full runtime framework. There output folder will contain ~45MB of files, which is why the --native switch will be useful in the future when it works properly. Deployment is a simple xcopy to the Pi file share, and execution only requires finding and running the .cmd file dnu creates in the approot folder.
Working with Windows IoT and the Pi is not quite what I remember from the old days of EEPROM burners and oscilloscopes. It’s too easy. But, there still is some magic in fiddling with a relatively raw piece of hardware.
There are 2 kinds of developers. Those who love conventions and those who loathe conventions. The former group sees conventions as a means to remove boilerplate code and expose the essence of software by avoiding ceremony. The later group tends to view conventions as dangerous magic. It’s also the later group, I’ve found, which tends to dislike the Startup class in ASP.NET Core applications.
public class Startup { public void ConfigureServices() { } public void Configure() { } }
Questions around Startup generally revolve around the following themes:
1. Why isn’t there a required interface available for Startup to implement?
2. How do I know what methods are needed and what parameters the methods will accept?
The short answer to both of these questions is that conventions offer more flexibility than contracts.
Programming against conventions is frustrating when you don’t know the conventions. The software won’t behave correctly, and in many convention oriented systems you won’t see any error message or know how to start debugging. Conventions are indistinguishable from magic.
Fortunately, for the startup scenario, the runtime does give you some actionable error messages when you miss a convention. For example, if you don’t have a proper class name for the startup code, ASP.NET will give you the following.
Here, the runtime will not only tell you what is missing, but also give you hints where you can find some wiggle room. You can have a dedicated startup class for any given environment, and use Startup itself as a default fall back. StartupDevelopment, StartupProduction, and StartupYourEnvironmentNameHere can all live in the same project and provide the startup configuration for their given environment name.
The same convention also applies to the Configure method in a startup class. In other words, once the runtime locates the startup class for the application, it will look for Configure and ConfigureServices methods that optionally have the environment name as a suffix.
One difference between Configure and ConfigureServices is that ConfigureServices is entirely optional. If you don’t provide the method, the runtime will carry on with only default services installed.
These types of conventions are impossible to enforce using interfaces. Attributes could make the purpose of a class more explicit, but attributes would add ceremony with little benefit.
Another difference between the Configure and ConfigureServices methods is how the ConfigureServices method can only take a parameter of type IServiceCollection. The Configure method, on the other hand, is an injectable method. You can take any number and types of parameters in Configure as long as the underlying IoC container can locate a service to populate the parameter.
public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IApplicationLifetime lifetime, IHostingEnvironment hostingEnvironment, IApplicationEnvironment applicationEnvironment) { // .... } }
The type of flexibility demonstrated by Configure is impossible to describe using a C# interface, and it is not the sort of flexibility you want to lose just to have a simplistic compile time check, at least not when the error messages are so explicitly good. Don’t worry about the conventions, the runtime will let you know when you goof.