Angular/Rails CRUD Tutorial Part 1

by Jason Swett,

The idea

I’ve decided to write a very long, comprehensive, multi-part tutorial. I came up with a fictional app called Cadence, a music lesson scheduling app. I wanted to think of something that would be a fitting use case for a single-page application, and I think a calendar-based application would make sense.

The tutorial starts with Angular by itself, no Rails.

The initial version

The initial version of this application will not be very impressive. You’ll be able to create “appointments”, each of which just consists of a date and client name. When you click Save, the appointment details will be added to a list of appointments on the screen. That’s about it. But as we’ll see, just doing that much is involved enough that we wouldn’t really want to bite off more than that for starters.

Since this initial version of the app is just Angular without Rails, we’ll be using localStorage as the data store.

We won’t even worry about tests yet in this initial version. We’ll first write a version without tests, because we already have enough to deal with without bringing tests into the picture, and then we’ll make a second pass with tests.

What you’ll learn

  • How to create an Angular project using Angular CLI
  • How to build components (and nested components)
  • How to use *ngFor to display lists
  • How to use services for inter-component interaction
  • How to use localStorage with Angular

We’re going to initialize this project using Angular CLI. We’re going to install Angular CLI using NPM, so if you don’t have NPM installed yet, you’ll need to install it before proceeding. (If you’re not familiar, NPM is a package manager for JavaScript. It’s kind of analogous to RubyGems for Ruby.)

The Angular CLI executable is ng. We can initialize our project with the ng new command, like this:

The format of the ng new command is ng new <your project name>. In this case we’re calling our project cadence.

Let’s cd into the cadence directory since everything we’ll be doing from this point on will happen inside this directory.

Angular CLI can also serve our new Angular application with ng serve.

After the server spins up, you can visit localhost:4200 and you should see a screen that looks like this:

Creating some components

In a moment we’ll be creating some components. What’s a component? I’ll try to give the simplest answer possible.

Imagine you have an application that has a datepicker thingy that you use in multiple places. Rather than pasting in the full datepicker code wherever you want the datepicker or referring to some include file everywhere you want the datepicker, you could just do something like this:

If you have an Angular component whose selector matches my-datepicker, Angular will go find the template for that component as well as the TypeScript code that defines the behavior for that component. To me this seems like a pretty natural and convenient way to invoke some behavior.

The Angular Style Guide recommends that we give our selectors application-specific prefixes. The idea is to avoid naming conflicts. So for our app called Cadence, we could put a cadence- prefix on each of our components. For example, we might have cadence-calendar or cadence-datepicker.

The people who built Angular CLI were apparently aware of this style guide recommendation because they built this kind of prefixing into Angular CLI. Angular CLI give us the ability to generate components via the ng generate component command. Each time we do this, Angular CLI will automatically give the component a cadence- prefix.

We can use the ng generate component command to generate our first component. Let’s generate a calendar component. As a reminder, this application we’re creating is a music lesson scheduling app. The calendar component will give us a place to put all our appointments.

Now that the component exists let’s get it to actually show up. The selector for the CalendarComponent is cadence-calendar. (If you look at src/app/calendar/calendar.component.ts, you can see the part near the top of the file where the selector for that component is specified.)

If we put
in any template file, it will show us CalendarComponent. Let’s put this selector in the AppComponent template now.

Now that we’ve made this change we should see a screen like this:

Adding Twitter Bootstrap

I like to use Twitter Bootstrap for most of the apps I create. Let’s just get adding Bootstrap out of the way now so that everything we do from this point on will look somewhat nice.

The first step is to install the Bootstrap NPM package. (The --save means we want NPM to add the bootstrap@next package to package.json so that Bootstrap is an explicit dependency of this project and will get installed anytime anyone does an npm install.)

Next we have to add a few lines to .angular-cli.json. Bootstrap comes with some styles and JavaScripts and we have to tell Angular CLI about these things in order for Bootstrap to get wired up properly.

After the very important step of restarting your server, you should see a screen like the one below. (To restart the server, kill the ng serve process and start it again.)

It’s also a good idea to put all our application’s content inside a container Let’s also add a header.

Adding NewAppointmentComponent

We haven’t yet put anything into CalendarComponent. The first thing we’ll actually put into it is another component. Angular recommends a component tree application structure where child components are nested inside of parent components. I thought it would make sense to make CalendarComponent contain a list of appointments as well as a component for creating new appointments. We’ll create that component for creating new appointments now.

First, let’s cd into the directory where CalendarComponent lives.

Now we can create NewAppointmentComponent itself.

Finally, we’ll put the selector for NewAppointmentComponent in the component for CalendarComponent. We should see NewAppointmentComponent‘s template content (presently just “new-appointment works!”) show up on the page.

Adding some form controls to the appointment form

Like I said near the beginning of this post, our appointments will only have two attributes for starters: date and client name. Let’s create two text inputs in NewAppointmentComponent‘s template, one for each of these attributes. Right now we’ll just accept arbitrary text and not worry about whether the date provided by the user is a valid date.

The form should look like this:

Make sure you’re in the calendar directory.

If you click Save, nothing happens, of course, We haven’t hooked up the Save button to anything.

The first step in getting the Save button to actually do something is to bind the form we just created to an Appointment object. We’ll bind the form to an Appointment, then when the user clicks Save, we’ll save that Appointment object (or, more precisely, we’ll save a representation of that Appointment object.)

If you’re wondering what this Appointment object is I’m talking about, it’s something that doesn’t exist yet. Let’s use Angular CLI to help us generate an Appointment class.

(We’re still in src/app/calendar, by the way.)

Then we’ll open up the Appointment class definition and add date and clientName properties. Why do we have public date?: string instead of public date: string? The question mark means those arguments are optional. So when we create an empty Appointment instance, we can instantiate it by doing new Appointment() instead of having to do new Appointment('', ''), which would feel kind of dumb.

After we define the Appointment class we’ll pull it into NewAppointmentComponent.

We’ve created a model property on NewAppointmentComponent and now we’ll bind to the Date input and model.clientName to the Client name input. If you’re interested in learning more about data binding I’d recommend this article.

We’re also adding a form and putting an event on the form. When the form gets submitted, the save() function on NewAppointmentComponent gets invoked. For now we’re just logging the model. I don’t want to try to do anything fancier than that yet because I want to be sure that this step works first.

If we try to reload the page now we’ll get an error in the console that says, “Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’.” This is because ngModel needs FormsModule in order to work but we haven’t imported FormsModule.

You can see in the screenshot below that I’ve filled out the form and clicked Save. In the console appears the Appointment object that corresponds to the values I entered in the form.

Saving data to localStorage

If you’ve never used localStorage before, don’t worry. It’s pretty simple to use and you don’t have to do anything special to use localStorage with Angular.

Below we’re creating array called appointments which, for now, only has one element: the Appointment object we’re saving from the form. Then we’re saving that array to localStorage.

If you save an appointment now, then open up the Application tab in the Chrome developer toolbar and go to Local Storage, you should be be able to see the appointment you just saved.

Showing the saved appointments in CalendarComponent

To get the saved appointments out of localStorage and into CalendarComponent, we can just do JSON.parse(localStorage.getItem('appointments')).

We can show the appointments on the page using an *ngFor loop.

Here’s what the page looks like with the appointments added. Not very nice-looking yet but we’ll improve the appearance shortly.

Preserving previously-saved appointments

Until now, NewAppointmentComponent saves an array of appointments that actually just consists of one element, the appointment that’s being saved right now. What it should really do is save an array of appointments consisting of all the existing appointments plus the appointment that’s being saved now. Let’s fix this.

Refactoring the appointment code into a service

The appropriate place to put business logic in Angular is in services. Components shouldn’t do very much. Components should only call services that do things. If there’s some saving of records going on, the component shouldn’t be aware of how that saving happens.

Let’s move our appointment-saving and appointment-retrieving code out of the components and into a service.

We’ll use Angular CLI to generate a service. Before you do so, make sure you’re in the calendar directory.

This command will generate a service called AppointmentService. Let’s create a function called save() which accepts an appointment. In the body of our function goes the code we’ve been using inside NewAppointmentComponent so far to save an appointment.

Then NewAppointmentComponent can just call the service’s save() function.

We’ll need to add AppointmentService as a provider in order for it to be able to be injected into components.

Similar to how we moved the saving code from the component to the service, we can move the retrieval code as well. Let’s create a getList() function in AppointmentService.

Then CalendarComponent can call getList().

Now that the getList() function exists, we can remove some duplication between the getList() function and the save() function by just calling getList() to get the list of appointments.

Getting the components to talk to each other

At this point, saving appointments works and getting appointments back out works but we have to refresh the page in order for our appointments to show up. This is of course not what we ultimately want. We want the saved appointments to show up on the page immediately.

We need to get NewAppointmentComponent and CalendarComponent to talk to each other. The Angular docs describe a method of inter-component communication where component A sends some data to a service, then component B gets that data out of the same service. At a high level, this is a simple enough concept to understand.

Where things start to get somewhat complicated is the fact that the example from the Angular docs use observables to achieve this communication. I’d recommend you take a look at my blog post Observables Made Simple before proceeding. It took me a long time to grasp observables. I think that post will help you understand them a little more quickly than I first did.

The way we’re going to use observables in this case is the following: when an appointment is saved, AppointmentService will emit that appointment. When the appointment is emitted, CalendarComponent will become aware of it because CalendarComponent has subscribed to the observable that emits appointments.

The first step is to add the observable to AppointmentService.

Then modify CalendarComponent so it subscribes to the appointment-emitting service and reloads the appointment list when it knows a new appointment has been saved.

Now when you save an appointment it will show up immediately.

Making it look nicer

It would be nice if the appointment form actually cleared itself when we save an appointment. We can do this by calling reset() on the form when the submit button is clicked.

A little padding would also help.

Lastly, we’ll give the appointment form a containing gray box. First we’ll give it a class name.

Then we’ll add the styles.

Then we’ll change the markup of the calendar page to make it look a little nicer.

Your application should now roughly match the screenshot below.


One thought on “Angular/Rails CRUD Tutorial Part 1

  1. manjul

    You are awesome, i did not get any tutorial with detailed understanding can u guide me with more angular concepts ?

    for example you have skipped, what does it mean by this “#appointmentForm” in this


Leave a Reply

Your email address will not be published. Required fields are marked *