How to create a chat group for anonymous users online

How to create a chat group for anonymous users online

Learn how to build an anonymous group chat with Angular 7

To follow this post, some basic knowledge of Angular is required. Since we’re using Angular we’re gonna also see some TypeScript code. Some basic knowledge here would also help. One would need Node 10 or any newer version installed, in order to play with the sample code from GitHub. That’s all, having this, following this tutorial should be straight forward.

We’ll not focus on the UI that much, more on the functional part, but here’s how it will look in the end:

Login screen for our demo app

Group screen for our demo app

The code is on GitHub here, in case you want to dive right in. Clone the repo and have fun, don’t forget to get back to the article to follow the tutorial 😉

New project

The first thing we have to do is create a new project so we can work on our awesome application. For this we need the Angular CLI, installed globally:

npm install -g @angular/cli

And then we can create the project:

ng new AngularChat

Or we can use npx, the node package runner. We achieve the same result, without having to install anything globally:

npx @angular/cli new AngularChat

Follow the interactive installation. Say yes to routing and pick CSS when asked what stylesheet format you want to use.

This will generate all the structure and code required for a new Angular application. It will also install all the dependencies. Once the command has finished running, you can open the new folder in your preferred editor(I love VsCode). You can start the local development server by running npm start or ng serve. The two commands do the same thing. Now you can go to http://localhost:4200 and see the application up and running.

CometChat Pro account

The second important thing that we need to do, is to create a free CometChat Pro account.

You can go to the website and click on the big red button that says “Get started for free”. Once you fill in all the required information you’ll have a trial account setup and ready to go.

On the CometChat dashboard, you’ll see an overview of your account. In the ‘Add new app’ dialog, enter a name and click the plus sign to create a new application. Take note of the Application ID as we’ll use it to communicate with the ComeChat API.

From the left side menu, go to API Keys, since we’ll have to create a new one for our application. Give it whatever name suits you, and select Auth Only as scope. Take a note of this API Key since we’ll use it in the application.

The CometChat app comes with five users and a group already created, so we have everything we need. The existing users are: superhero1, superhero2, superhero3, superhero4 and naturally, superhero5. One group that would fit all these five is supergroup. You can see them all using the CometChat dashboard.

CometChat SDK

With all this in place, we now add the CometChat package to our application. This will help us work more easily with the API. Instead of us having to make all the calls we can use pre-made functions for the operations that we want to make.

To add the package run:

npm install @cometchat-pro/chat

Now we can reference the library in our project, and use whatever functions we need from there in our code:

import { CometChat } from '@cometchat-pro/chat';
TypeScript type definitions

At the time of this writing, the library does not have TypeScript type definitions. Though this is something that might come 😉 .

All Angular/TypeScript developers love type definitions. To make it easier to follow the tutorial and play with the code, I’ve created a few, for the functions that we’re going to use.

This was done by creating a new *.d.ts file inside the src folder of our app. The TypeScript compiler will pick it up and show us the type definitions when working with the code. This is not something you need to do, but if curious you can have a look at the file on GitHub.

Application structure

Now let’s think about our application a bit, we want an anonymous chat, so this will be a component. But before we get to this component we also want to allow the user to login to our application. So we’ll need another component for that. Also it’s a best practice to wrap the usage of a library inside a service, so we’ll need a CometChat service class also.

With this in mind, we’ll use the Angular CLI to generate these components for us. If you installed the CLI globally at the beginning you can use the ng command. If not, you can use the locally installed one by running npm run ng.

Now to generate our components:

ng generate component components/Login
ng generate component components/GroupView

We pass the generate argument first, to tell the CLI what we want to do. Then we specify the blueprint of what we want to generate, in this case a component. Then we specify the name of the component. In our case I’ve also added components/ before the actual name so that all the components are in the same folder.

To create the service class:

ng generate service services/CometChat

Same thing as before. We changed the blueprint to service this time and specified a services folder for this class to be in.

Now we have the structure of our application in place.


We have our two components in place, now we have to tell Angular when to load them.

In our App routing module (app-routing.module.ts) we can update the routes like this:

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'chat', component: GroupViewComponent },

The first one is a redirect when our application starts we want to go to the login path. The second one tells Angular that whenever we go to login we want to show the LoginComponent. The second one does the same but with the chat path and the GroupViewComponent.

We can now go on and implement some functionality in our application.

Initialising CometChat

The first thing we need to do to use the CometChat SDK is to initialise it. This has to be done before calling any other methods. Due to this, a good place to implement it would be when our application initializes. Meaning the ngOnInit hook of the app component.

In our CometChat service, we create an init method. It will have only one parameter, the application ID. Inside, we’ll call the init method of the CometChat library:

init(apiKey: string) {
    msg => console.log('Initialized succesfull: ', msg),
    err => console.log('Initialization failed: ', err),

The init method will return a Promise. While it’s not mandatory, it’s a good practice to handle the result using a then call. Printing some messages in case of success or failure is enough for us to make it easier to debug the code.

In our app component we have to add the service as a parameter to the constructor:

constructor(private cometChat: CometChatService) {}

You can notice that before the name there is the private access modifier. This is a nice little trick in TypeScript that allows us to create a field with this name on the class.

We can move on and initialise CometChat when our application starts, so in the same app component:

ngOnInit() {
  this.cometChat.init('CometChatApp ID');

Global config values

It’s a good practice to keep global values in the same file. A good place to do this is the angular environment config files(environment.ts). We already have an object called environment there. We can add a property on it with the values for the CometChat application id and API key:

export const environment = {
  production: false,
  cometChat: {
    apiKey: 'API_KEY_HERE',
    appId: 'APP_ID_HERE',

This will allow us to reference them through the application whenever needed. So in the example above, instead of hardcoding the value we can do:

Login component

Everything is initialized. Now we can move on and allow the user to authenticate to our application.

For this we are gonna use the login function from CometChat. This allows a user to be authenticated based on a user id and API key. Even though this is an anonymous chat app, we need to authenticate to the CometChat API so that we can read and write information related to our application.

Inside our CometChat service, we create a new login method and perform the call:

login(userId: string) {
  return CometChat.login(userId, environment.cometChat.apiKey)
    user => console.log('Login succesfull: ', user),
    err => console.log('Login failed: ', err),

We pass in the user id and use the API key from the environment object. And as we did before, we handle the outcome Promise result by writing some values in the console. This method also returns the result of the API call. We handle it here, but we also want to know where we use it if it’s successful or not.

When successful, the result of this method call will be the logged in user. It might be useful to hold onto it. So let’s create a local user property and assign it when we have a response.

user => {
  console.log('Login succesfull: ', user);
  this.currentUser = user;

With this in place we can move on and add an input where the user can enter a name and a submit button. In our login component html template we’ll have this code:


Join chat

When the user clicks the ‘Join chat’ button, we will take the text value from the input and call the login method in our class. As we did in the application component. We have to use dependency injection to get an instance of the CometChat service:

constructor(private cometChat: CometChatService, private router: Router) {}

We also have the Angular Router there since we’ll use it to navigate to the group chat page.

Inside the login method, we’ll call the CometChat service. If the login is successful, we redirect the user to the chat page:

login(userId: string) {
    .then(() => this.router.navigateByUrl('chat'))

If everything goes ok, once a user enters a valid name and hits join they can get to our group view component.

Group view component

This is our most complex component and where most of the action will take place. We’ll be able to see messages here and write new ones.

To make things easier we’ll start with the template. We need a list, to show all the messages and an input with a button, to allow users to write new messages. For the list of messages we can have something like this:

    *{{ message.sender.uid }}* 

    {{ message.text }}

We iterate over messages collection using the ngForOf directive from Angular. For each message, we show the sender uid. This means the name of the user that wrote the message, and the text of the message.

We also use the ngClass directive to add a css class only to messages that were written by the logged in user. This is something we’re used to from most chat apps. Usually, they have a different color or placed in a different position on the screen.

For this to work we need to have the properties defined in our class:

messages = [];
get currentUser() {
  return this.chatService.currentUser;

Here we can see where we’re actually using the currentUser that we’ve stored when the login is performed.

As before, the CometChat service is added in the constructor as a parameter:

constructor(private chatService: CometChatService) {}

Good, now we also have to show some messages 🙂. There are two parts to this, we need to fetch existing messages, that were written before. And after that, we need to register a listener for any new message that might arrive.

Previous messages

To fetch messages, we need to build something like a query and specify what we want to retrieve. The SDK has the MessagesRequestBuilder class that allows us to do exactly this.

We have different methods on it, in a fluent-like API, that allows us to set different properties for our request:

  • number of messages to retrieve
  • user or group id
  • filtering methods like timestamp or message id

In our case we want to fetch messages from a group, so we need to specify only the group id. Ok, maybe a limit would also be a sensible thing to add 😃. After we’ve set all the properties we want we can call the build method. This will create the query and give us back an instance of MessageRequest that we can use to fetch messages:

getPreviousMessages(groupId: string) {
  const messageRequest = new CometChat.MessagesRequestBuilder()
    return messageRequest.fetchPrevious();

The message request class has two methods: fetchNext and fetchPrevious. As the name suggests, next will get messages after the filters, similar to greater than. Previous will get the messages before, or lower than.

In our case, we did not set any filter so any of the two should work. The method above was added to the CometChat service class. We can call it in our group view component to fetch the previous messages:

  .then(messages => (this.messages = messages))

When we get the response back, we assign the messages to the local property. Angular will notice there is something new and will render our component with the new values.

Message listener

We already have messages that were previously written, but we also want to show incoming, real-time, messages. Messages that other users might write as we look at the screen. To get them we need to register a message listener. For this we need a unique listener ID. Something related to the screen or part of the application the chat is linked to. We can then use the MessageListener class to register handlers for different type of messages:

listenForMessages(listenerId: string, onMessageReceived: (msg: any) => void) {
    new CometChat.MessageListener({
      onTextMessageReceived: onMessageReceived,

For now, we only care about text messages. That’s the only listener we’ve registered. But it also has properties like onMediaMessageReceived and onCustomMessageReceived for other types.

Having added the above method to the CometChat service class, we can use it in our group view component. After we’ve read all the previous messages, we can listen for new ones:

this.chatService.listenForMessages(this.listenerId, msg => this.messages.push(msg));

We have a local property listnerId. With a value of ‘Web_App_Listener_Group_ID’, but you can use pretty much any value you want. This should be an unique value for our application, but since we have only one listener, we’re safe. As a method, we pass a function that will take any new message and add it to our messages array. Again, this will trigger the component to be rendered and we’ll see new messages on the screen.

It’s a good practice to remove message listeners when they are no longer needed. So let’s do that.

In our CometChat service we add the remove method:

removeListener(listenerId: string) {

And in our group view component, we add a handler for the destroy event and call it there:

ngOnDestroy(): void {

Adding new messages

The last part we need to do is write new messages and send them to the server.

First, we need to update the template with an input and button for this:


When the user clicks the ‘Send’ button, we take the text from the input and call the sendMessage method on our class. As a bonus we also clear the input value, to allow the user to write a new message.

To send the message we have to use the, you guessed it, sendMessage function. Before we send the message we have to create it:

const message = new CometChat.TextMessage(

This is an example of how to send text messages. The first value, receiverId, is the user or group id of whom we want to send the message to. Second, and the easiest one, is the text content of the message.

The third one is the type of the message, in our case, text. It can also be file, image, video or audio.

The last value represents the type of receiver, either a user or a group. In our case a group.

Once we have the message created, we send it to the server:


This was the sendMessage function, implemented inside the CometChat service class. You can have a look at the code here.

With this function in place we can go to our group view component and implement the sendMessage function there:

sendMessage(message: string) {
  this.chatService.sendMessage('supergroup', message);

One thing to keep in mind. The messages the user is sending will not get back into the message listener that we’ve registered. To see them on the screen after they are sent we have to manually add them to the messages array:

  text: message,
  sender: { uid: this.currentUser.uid }

That was it! Now we can receive and send messages in our super group 🙂.


This was a way to create a generic anonymous chat application with Angular and CometChat. You’ve went through the basics of using CometChat in an Angular context. Now can build on this and extend your application with new and cool capabilities.

Group screen with messages

The sample code on GitHub contains a bit more error handling and some basic css to make everything a bit more tidy. Don’t hesitate to check it out 😉.

Angular Tutorial - Learn Angular from Scratch

Angular Tutorial - Learn Angular from Scratch

Angular Tutorial - Learn Angular from Scratch: This course is for beginners who are curious on how to get started with Angular. In this course you will learn how to download, install and play around with Angular. We teach you the main components of Angular, so that you can get up and running with it asap. You will learn now to start building applications with Angular.

This course is for beginners who are curious on how to get started with Angular. In this course you will learn how to download, install and play around with Angular. We teach you the main components of Angular, so that you can get up and running with it asap. You will learn now to start building applications with Angular.

Learning Angular can be a daunting experience that's why this course was created; to give you an easier learning experience with it.

What am I going to get from this course?

  • You will learn the mayor fundamentals of Angular
  • You will learn how to get up and running with Angular
  • You will learn to create Applications using Angular 5 and beyond

What you'll learn

  • You will learn the mayor fundamentals of Angular
  • You will learn how to get up and running with Angular
  • You will learn to create Applications using Angular 5 and beyond

An Angular Roadmap — The Past, Present, and Future of Angular

An Angular Roadmap — The Past, Present, and Future of Angular

✅Interested in being an Angular developer in 2019? ... blog post it's most likely that you've written some code in javaScript in the past.

Paleolithic JavaScript — SproutCore

In the beginning, there was SproutCore. It was the first comprehensive JavaScript framework aimed at making it easy to build desktop-quality single-page web apps. It’s not that this wasn’t possible before. When Google released Gmail, it showed the world that web apps really could replace complex desktop applications. Google even open-sourced the Closure toolkit — a set of libraries and an optimizing compiler that it used to build Gmail.

The problem was that Google’s Closure tools weren’t very developer-friendly. They relied heavily on Java, which alienated web developers who were used to working with JavaScript, PHP, Ruby, and Python. Gmail was a great demonstration of what was possible, but developing similar applications still felt out of reach for many.

Some courageous developers managed to string together amazing single page apps using a combination of jQuery, duct tape, and hope. While these apps looked amazing to end-users, for the developers working on them, the apps quickly turned into hulking piles of technical debt that made the dev team dread heading to work in the morning.

As a result, a few enterprising developers began to work on frameworks that would bring Gmail-like apps within easy reach of web developers everywhere. SproutCore was the first of these frameworks to take off. It came with a complete set of widgets that made it possible to build complex web applications without even touching HTML or CSS.

This ended up being great for former desktop developers who had been dragged kicking and screaming onto the web. Several more frameworks popped up with similar goals; GWT and Cappuccino were the most prominent. These frameworks even avoided JavaScript by transpiling other languages into JS. Again, this was great for desktop developers. But it left passionate web developers out in the cold and made them feel as though their hard-won HTML, CSS, and JavaScript skills weren’t valuable.

This left an opening for a framework that truly embraced the web, instead of trying to plaster over it and pretend it was something else. A couple of early frameworks (Backbone and Knockout) appeared, and achieved a moderate amount of success. Ember also showed up around this time. It took SproutCore, stripped it down to its bones, and tried to rebuild it into something truly web-friendly. Ember wanted to be the Six Million Dollar Man of the JavaScript world: rebuilt better, stronger, and faster.

None of these frameworks rocketed to popularity. The world was waiting for something better. In 2010, that something better appeared — it was named Angular.

The Golden Age of Angular

Even before Angular version 1.0 had been released, Angular took the front-end development world by storm. Finally, we had an easy-to-use JavaScript framework that treated HTML as a first-class citizen. Developers and designers could now work together to build amazing single-page applications. This came as a relief to designers, who had been annoyed and offended because older frameworks had treated HTML and CSS as tools for barbarians, tools that no civilized developer should have to touch.

The first thing that seemed magical to developers trying Angular for the first time was two-way data binding. Prior to this, most developers had only seen this kind of data binding in desktop frameworks like WPF and Windows Forms. It was great to be able to bind forms and other UI elements to JavaScript model objects. While two-way data binding could cause performance problems when overused, teams that used it judiciously found that Angular enabled them to create complex front-end applications much more quickly than ever before.

Angular proved to be popular for more than just easy binding of data to HTML elements. Angular directives provided an easy way to create reusable HTML + CSS components. Although other JavaScript frameworks provided this before Angular, Angular was the first one that became extremely popular. Reusable components had long been in-use in server-side frameworks. ASP.NET user controls and partial templates in Rails and Django are but a few examples.

Finally, Angular made dependency injection popular in the front-end development world. Dependency injection had long been popular in enterprise applications, which is perhaps why it hadn’t caught on in the JavaScript world. Front-end developers have long been averse to what they see as needlessly complex enterprise software design patterns. This concern isn’t without merit. Have you ever, in the course of writing an application, said to yourself “What I really need here is a “SimpleBeanFactoryAwareAspectInstanceFactory?”

Dependency injection, though, has proven its worth. And Angular made dependency injection easy to use for an audience that hadn’t used it much in the past. Need an HTTP client? Or perhaps you’d like to do some animation? No problem. Angular had built-in services for those. Just ask for them, and Angular would inject them into your components. No need to instantiate anything yourself.

Or perhaps you wanted to use the browser’s window or location objects without making it impossible to unit test your components outside of a browser? Angular had you covered there too, with its built-in $window and $location services. At runtime, you’d get the browser objects you were expecting. And when running unit tests server-side in Node.js, you could pass mock services into your components to ensure they behaved as expected in various scenarios.

If all of this wasn’t enough, Angular also made it simple to register and inject your own services. For developers who were used to binding all their data to the DOM and hoping for the best, this was awesome. If you were writing a new front-end app that called for APIs that would cost your company a lot of money if overused, you’d probably prefer to be able to write tests ahead of time to ensure that your application doesn’t try to do something like calling the Twilio API 800 million times.

So you’d create a Twilio service that gets injected at runtime. At testing time, you’d create a mock service that records the cost of every API call your application is trying to make. You’d write tests that cover common usage scenarios and ensure that these scenarios don’t result in your company receiving a 7-figure bill. Overall, most developers found that Angular directives combined with dependency injection made it possible to write modular, testable front-end applications using tried-and-true software engineering techniques. Many development teams decided that this resulted in a happy state of affairs, and decided to go all-in on Angular.

The Angular Decline? The Rise of React

While things were mostly great in the world of Angular, it wasn’t all sunshine and lollipops. Developers were starting to run into severe performance problems when they tried to bind too many model objects to too many DOM elements. Some applications slowed to a crawl. Direct calls to $digest and other black-magic sorcery started becoming necessary to achieve acceptable performance. Around the same time, a new challenger appeared: React. At first, React didn’t seem to pose too large a danger to Angular. After all, these React weirdos had gone to the trouble of inventing JSX, which looked a lot like a way to mix markup into your code. Hadn’t we gone to a lot of trouble to invent templating languages for the explicit reason of avoiding mixing markup and code?

As it turned out, React’s approach was pretty popular in the front-end development community. It didn’t rocket to popularity, however. Angular was still dominant, and it looked like it would remain that way. Until that is, Angular’s popularity was given a good kick in the teeth from an unexpected source: the Angular team itself.

The Introduction of Angular 2

Angular 2 was first announced at the ng-europe conference in 2014. The Angular team’s plans came as a shock to the Angular community, to say the least. Reaction from Angular developers was swift and negative… and not without reason. Angular 2 would be getting rid of many familiar concepts from Angular 1, introducing a new, incompatible templating language (and oh, by the way) would also be programmed using an entirely new language.


Although both Angular 1 and Angular 2 were called ‘Angular,’ in reality, they were very different frameworks with a few things in common. To help prevent confusion, the Angular team started referring to the old version of Angular as ‘AngularJS’, and the new version as simply ‘Angular.’ This makes intuitive sense since AngularJS was written in JavaScript, and Angular was not. To keep the distinction between the frameworks clear, I’ll be referring to Angular 1 as AngularJS from this point forward.

As a result of all of this, AngularJS developers lost faith in the framework’s future. They threatened to move to a new framework on future projects, and that is precisely what many of them did. React was the biggest beneficiary of the mass exodus from AngularJS.

Although React didn’t do as much as AngularJS, in a way that was positive. If you’re using a view library that doesn’t try to include everything plus the kitchen sink, it’s a lot more difficult for the developers of that library to pull the rug out from under you in the future. In the beginning, using React was a bit of a pain compared to AngularJS. You had to cobble together a patchwork of libraries just to cover the functionality the AngularJS provided out of the box.

Many teams saw this as a good way to reduce risk, because it was unlikely that the developers of all of those libraries would decide to make backward incompatible breaking changes at the same time, which is essentially what Angular had done.

The Emergence of Vue

To compound AngularJS’ woes, another framework named Vue showed up at about the same time the drama over Angular 2 was occurring. Vue was inspired by AngularJS but aimed to simplify it and get rid of what Vue’s creator saw as unnecessary complexity (so Vue felt very familiar to existing AngularJS developers). Vue provided a safe haven for many AngularJS developers who didn’t want to move over to React.

This doesn’t mean that AngularJS developers were not waiting patiently for Angular 2 to appear. But it’s clear that there was a mass exodus from AngularJS to React and Vue due to the uncertainty caused by the plans for Angular 2.

Rising From the Ashes with Angular 2

Eventually, Angular 2 was released. As expected, it did away with many familiar concepts from AngularJS but kept a few of the best pieces like services and dependency injection. Fortunately for the sanity of developers, Angular uses plain TypeScript and not a fork as originally planned.

To make things more confusing, the Angular team maintained a fork of the new framework that used the Dart programming language instead of TypeScript. Initially, the TypeScript and Dart versions were developed in sync, generated from a single code base. Eventually, the TS and Dart versions of Angular decided to go their separate ways, and Angular Dart now exists on its own.

Even with this confusion, Angular’s popularity began to increase again after the Angular 2 release. It happened slowly. As often occurs in software development, trends shifted. Developers realized that a big, batteries-included framework might actually be useful. After all, when your application grows large enough, you end up actually needing all of those batteries.

Enterprise developers, in particular, began moving back to Angular. This makes sense. Usually, when you start an enterprise web app, you know it is going to be complex. There’s no point in starting with a tiny MVP when you know from the beginning all 87 things your application is going to be expected to do.

Where’s Angular 3?

Although Angular 2 wasn’t perfect, many developers of complex web applications began to realize that the new-and-improved Angular was a good fit for their needs. Fortunately for them, Angular had some exciting improvements in store. More importantly, the Angular team demonstrated that it could consistently publish new versions of the framework with few breaking changes between versions

In a move that seemed odd at the time, the Angular team decided to skip version 3 entirely and move to version 4. This was done for good reason: the team working on Angular’s router package had already pushed ahead and released version 3, while the remainder of Angular was still at version 2.3. They decided to keep all Angular package versions in sync moving forward, and bumping everything up to version 4 for the next release was the easiest way to achieve this.

Angular 4

Angular 4 had some significant changes, including added ahead of time compilation, which resulted in small production JavaScript bundles and shorter application load time. Support for server-side rendering was added, which was a boost for teams that wanted to render their app ahead of time to improve initial load performance. Many other improvements were added throughout the framework, but upgrading apps from Angular 2 to 4 was quick and painless in most cases.

Angular 4.3 and Angular 5

Angular 4.3 added a new HTTP client that was easier to use than the old HTTP service. In Angular 5, the old HTTP service was deprecated and would be dropped in the next release. In spite of this inconvenience, there was relatively little grumbling because the upgrade in most cases was straightforward. Angular 5 also added better internationalization support and further build optimizations.

Angular 6 and 7

Angular 6 and 7 were disappointing to some developers. There were no large changes, but there were many small quality of life improvements, especially to the Angular CLI tooling. The decreasing number of visible changes isn’t an indication that the Angular team has stopped innovating. Instead, it shows that the framework is mature, so the development team is now free to do more work behind the scenes, fixing bugs and improving performance.

The stability of the framework since the release of Angular 2 has drawn some old-school AngularJS developers back into the Angular world. It has also attracted the attention of enterprise development teams. When you’re building enterprise apps that may live for decades it’s ideal to use a framework that gets new releases on a predictable schedule but doesn’t change too rapidly. A developer who had only used Angular 2 could be up and running and contributing to an Angular 7 app within minutes.

The Future of Angular

Angular 8 and Angular Ivy

And that brings us to today. As we’ve seen, Angular has come a long way. It has gone from loved by web developers to being reviled to being admired, although it isn’t yet loved again like it was in its early days.

On the horizon, we have Angular 8. A ton of work has been done in Angular 8 to make it easy to use with the Bazel build system, which is absolutely amazing news for all 3 developers who are using it outside of Google. More excitingly, though, the Angular team is hard at work on a new rendered called Angular Ivy. It’s intended to be a drop-in replacement for the current rendered. For the most part, current apps won’t need to make any changes to use Angular Ivy.

If Angular Ivy is a drop-in replacement, why should developers care? Two important reasons: speed, and bundle size — two very important concerns. For a few years, it seemed like web developers had gone a bit crazy. Teams were shipping JavaScript bundles that were 5MB, 10MB, or even larger, and thinking that there was no problem with this. After all, the applications worked perfectly on the developers’ i7-powered MacBook Pros so they should work fine for everyone, right?

Unfortunately, in the real world, not everyone is running the latest and greatest hardware. Hundreds of millions of people access the internet solely on older Android phones with slightly more processing power than a potato, through internet connections only a little faster than dial-up. For these users, a huge JavaScript bundle takes forever to load, and even longer for their device to parse and run. Even in less extreme cases, there are countless users around the world who aren’t using the latest and greatest hardware. For them, massive JavaScript apps are usable (but painful).

Angular Ivy Expectations

The Angular Ivy renderer will help in several ways:

  1. It is being written with an eye on efficiency, so it will accomplish the same tasks while executing far fewer CPU instructions. This will improve both the battery life and the sanity of users with less-than-powerful devices.
  2. The renderer will be written in a much more modular fashion that the current renderer. This will make it much more amenable to tree-shaking and dead code elimination. As a result, your production JavaScript bundle will include only the code that is needed to run your application, instead of bundling together everything plus the kitchen sink as often happens with the current rendered.
  3. In addition to the bundle-size reduction and improved rendering speed, Angular Ivy has another few quality-of-life enhancements for Angular developers. Rebuild times are significantly faster. So if you’re running your app in development mode and waiting for your changes to appear, you’re now going to be spending a lot less time waiting.
  4. Template-type checking is improved, which means you’ll catch more errors at compile time instead of at runtime. Runtime template bugs are annoying, because they either bite you during testing, or they bite your users when they’re trying to use your app.
  5. The Angular Ivy template compiler will generate code that is human readable, which the current View Engine compiler doesn’t do. This will come in handy when trying to track down tough template bugs.

The net result: smaller apps, faster apps, happier developers, and happier users.

Angular’s Past, Present, and Future

If you’ve been using Angular from its early days all the way until now, then congratulations! While there have been plenty of rough patches, we’ve ended up with a fast, modern framework that is fun to use.

If you were an AngularJS developer but moved on to React, Vue, or something else, I encourage you to give Angular another look. It’s worth your time, even if you decide to stick with what you’re using now.

And if you’ve never used Angular at all, why not give it a shot?

We’ve just been on a whirlwind tour through Angular’s past, present, and future. Without a doubt, it has been quite a ride. Regardless of your Angular background, I hope you’ve enjoyed the tour!

30s ad

Angular 2 Firebase - Build a Web App with Typescript

Angular 2 Demystified

Master Angular 2 - The No Nonsense Course

Complete Angular 7 - Ultimate Guide - with Real World App

A Quick Guide to Angular 7 in 4 Hours

Angular 7 Tutorial - Learn Angular 7 by Example

Angular 7 Tutorial - Learn Angular 7 by Example

Watch or read this full crash course on learning Angular 7, tutorial is perfectly suited towards a beginner with no prior Angular experience.

Watch or read this full crash course on learning Angular 7, tutorial is perfectly suited towards a beginner with no prior Angular experience.

Ever since the release of Angular 2, I have created a full course for each new iteration. Today is no different, as Angular 7 just released!

With this beginner’s crash course, I make the assumption that you have never worked with Angular before. Therefore, this tutorial is perfectly suited towards a beginner with no prior Angular experience. The only thing you should be familiar with is HTML, CSS and JavaScript.

In this course, you’re going to discover just how powerful Angular 7 is when it comes to creating frontend web apps. Let’s get started!

If you prefer watching a video…

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.


You’re first going to need to install the Angular CLI (Command Line Interface) tool, which helps you start new Angular 7 projects as well as assist you during development. In order to install the Angular CLI, you will need Nodejs. Make sure you install this with the default options and reload your command line or console after doing so.

In your command line, type:

> npm install -g @angular/cli

Once complete, you can now access the CLI by simply starting any commands with ng.

Hop into whichever folder you want to store your projects, and run the following command to install a new Angular 7 project:

> ng new ng7-pre

It’s going to present you with a couple questions before beginning:

? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS   [   ]

It will take a minute or two and once completed, you can now hop into the new project folder by typing:

> cd ng7

Open up this project in your preferred code editor (I use Visual Studio Code, and you can launch it automatically by typing code . in the current folder), and then run this command to run a development server using the Angular CLI:

> ng serve -o

-o is for open, this flag will open your default browser at http://localhost:4200. Tip: You can type ng to get a list of all available commands, and ng [command] --help to discover all their flags.

Awesome! If all went smooth, you should be presented with the standard landing page template for your new Angular 7 project:

Angular 7 Components

The most basic building block of your Angular 7 application (and this is a concept that’s not new) is the component. A component consists of three primary elements:

  • The HTML template
  • The logic
  • The styling (CSS, Sass, Stylus, etc…)

When we use the Angular CLI to start a new project, it generates a single component, which is found in /src/app/:


While we have three files here that represent the three elements above, the .ts (TypeScript) is the heart of the component. Let’s take a look at that file:

import { Component } from '@angular/core';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
export class AppComponent {
  title = 'ng7-pre';

Here, because this is a component, we’re importing Component from the @angular/core library, and then it defines what’s called a @Component decorator, which provides configuration options for that particular component.

As you can see, it’s referencing the location of the HTML template file and the CSS file with the templateUrl property and the styleUrls property.

The logic of the component resides in the class at the bottom. As you can see, the CLI starter template simply defines a single property called title.

Let’s use the Angular CLI to create our own components that we’ll need going forward. In the console, issue the following commands:

> ng generate component nav
// output

> ng g c about
// output

> ng g c contact
// output

> ng g c home
// output

Notice we first use the full syntax to generate a component, and then we use a shorthand syntax, which makes life a little bit easier. The commands do the same thing: generate components.

When we generate components this way, it will create a new folder in the /src/ folder based on the name we gave it, along with the respective template, CSS, .ts and .spec (for testing) files.

Angular 7 Templating

You may have noticed that one of the components we generated was called nav. Let’s implement a header bar with a navigation in our app!

The first step is to visit the app.component.html file and specify the following contents:



So, we’ve removed a bunch of templating and placed in , what does this do and where does it come from?

Well, if you visit /src/app/nav/nav.component.ts you will see that in the component decorator, there’s a selector property bound to the value of app-nav. When you reference the selector of a given component in the form of a custom HTML element, it will nest that component inside of the component it’s that’s referencing it.

If you save the file you just updated, you will see in the browser we have a simple, nav works! And that’s because the nav.component.html file consists of a simple paragraph stating as much.

At this point, let’s specify the following HTML to create a simple navigation:

  <div class="container">
    <a routerLink="/" class="logo">apptitle</a>
        <li><a routerLink="/">Home</a></li>
        <li><a routerLink="/about">About</a></li>
        <li><a routerLink="/contact">Contact us</a></li>

The only thing that might look a little strange is routerLink. This is an Angular 7 specific attribute that allows you to direct the browser to different routed components. The standard href element will not work.

While we’re here on the subject of templating, what if we wanted to display properties that are coming from our component? We use what’s called interpolation.

Make the following adjustment to our template:

<!-- From: -->
<a routerLink="/">myapp</a>

<!-- To: -->
<a routerLink="/">{{ appTitle }}</a>

Interpolation is executed by wrapping the name of a property that’s defined in the component between {{ }}.

Let’s define that property in nav.component.ts:

export class NavComponent implements OnInit {

  appTitle: string = 'myapp';
  // OR (either will work)
  appTitle = 'myapp';

  constructor() { }

  ngOnInit() {


You can use the TypeScript way of defining properties or standard JavaScript. Save the file and you will see myapp is back in the template.

There’s a lot more to templating, but we will touch on those topics as we continue. For now, let’s apply style to our header.

First, let’s visit the global stylesheet by opening /src/styles.scss and define the following rulesets:

@import url(',700');

body, html {
    height: 100%;
    margin: 0 auto;

body {
    font-family: 'Montserrat';
    font-size: 18px;

a {
    text-decoration: none;

.container {
    width: 80%;
    margin: 0 auto;
    padding: 1.3em;
    display: grid;
    grid-template-columns: 30% auto;

    a {
        color: white;

section {
    width: 80%;
    margin: 0 auto;
    padding: 2em;

Visit nav/component.scss and paste the following contents:

header {
    background: #7700FF;

    .logo {
        font-weight: bold;

    nav {
        justify-self: right;

        ul {
            list-style-type: none;
            margin: 0; padding: 0;

            li {
                float: left;

                a {
                    padding: 1.5em;
                    text-transform: uppercase;
                    font-size: .8em;

                    &:hover {
                        background: #8E2BFF;

If you save and refresh, this should be the result in the browser:


Angular 7 Routing

Now that we have a navigation, let’s make our little app actually navigation between our components as needed.

Open up /src/app/app-routing.module.ts and specify the following contents:

// Other imports removed for brevity

import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },

// Other code removed for brevity

As we can see here, we’re defining importing our components and defining an object for each route inside of the routes constant. These route objects also accept other properties, which allow you to define URL parameters, but because our app is simple, we won’t be doing any of that.

Save this file and try clicking on the links above. You will see that each of the respective component’s HTML templating shows up in the  defined in app.component.html.

This is what the result should look like in the browser at this point:

You now know enough about Angular 7 to create a very simple website with routing! But let’s learn more than that.

Angular 7 Event Binding

In the next several sections, we’re going to use our /src/app/home component as a playground of sorts to learn features specific to Angular 7.

One of the most used forms of event binding is the click event. You often need to make your app respond when a user clicks something, so let’s do that!

Visit the /src/app/home/home.component.html template file and specify the following:


<button (click)="firstClick()">Click me</button>

You define an event binding by wrapping the event between (), and calling a method. You define the method in the home.component.ts file as such:

export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {

  firstClick() {


Save it, get out the browser console (CTRL+SHIFT+i) and click on the button. The output should show clicked. Great!

You can experiment with the other event types by replacing (click) with the names below:







Angular 7 Class & Style Binding

Sometimes you may need to change the appearance of your UI from your component logic. There are two ways to do this, through class and style binding.

There are a lot of different methods you can use to control class binding, so we won’t cover them all. But I will cover some of the most common use cases.

Let’s say that you want to control whether or not a CSS class is applied to a given element. Update the h1 element in home.component.html to the following:

<h1 [class.gray]="h1Style">Home</h1>

Here, we’re saying that the CSS class of .gray should only be attached to the h1 element if the property h1Style results to true. Let’s define that in the home.component.ts file:

  h1Style: boolean = false;

  constructor() { }

  ngOnInit() {

  firstClick() {
    this.h1Style = true;

Let’s also define the .gray class in this component’s scss file:

.gray {
    color: gray;

Save it, and you can now click on the click me button to change the color of the Home title.

What if you wanted to control multiple classes on a given element? You can use ngClass. Modify the home component’s template file to the following:

<h1 [ngClass]="{
  'gray': h1Style,
  'large': !h1Style

Then, add the large ruleset to the .scss file:

.large {
    font-size: 4em;

Now give it a shot in the browser. Home will appear large, but shrink down to the regular size when you click the button. Great!

You can also control appearance by changing the styles directly from within the template. Modify the template as such:

<h1 [style.color]="h1Style ? 'gray': 'black'">Home</h1>

Refresh and give this a shot by clicking the button.

Like ngClass() there’s also an ngStyle() that works the same way:

<h1 [ngStyle]="{
  'color': h1Style ? 'gray' : 'black',
  'font-size': !h1Style ? '1em' : '4em'

Give this a go! Awesome!

Angular 7 Services

Services in Angular 7 allow you to define code that’s accessible and reusable throughout multiple components. A common use case for services is when you need to communicate with a backend of some sort to send and receive data.

> ng generate service data

Open up the new service file /src/app/data.service.ts and let’s create the following method:

// Other code removed for brevity

export class DataService {

  constructor() { }

  firstClick() {
    return console.log('clicked');

To use this in a component, visit /src/app/home/home.component.ts and update the code to the following:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
export class HomeComponent implements OnInit {

  constructor(private data: DataService) { }

  ngOnInit() {

  firstClick() {;


There are 3 things happening here:

  • The HTML template
  • The logic
  • The styling (CSS, Sass, Stylus, etc…)

If you try this, you will see that it works as clicked will be printed to the console. Awesome! This means that you now know how to create methods that are accessible from any component in your Angular 7 app.

Angular 7 HTTP Client

Angular comes with its own HTTP library that we will use to communicate with a fake API to grab some data and display it on our home template. This will take place within the data.service file that we generated with the CLI.

In order to gain access to the HTTP client library, we have to visit the /src/app/app.module.ts file and make a couple changes. Up until this point, we haven’t touched this file, but the CLI has been modifying it based on the generate commands we’ve issued to it.

Add the following to the imports section at the top:

// Other imports
import { HttpClientModule } from '@angular/common/http';

Next, add it to the imports array:

  imports: [
    HttpClientModule,    // <-- Right here

Now we can use it in our /src/app/data.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';  // Import it up here

  providedIn: 'root'
export class DataService {

  constructor(private http: HttpClient) { }

  getUsers() {
    return this.http.get('')
} is a free public API that we can use to grab data.

Open up our home.component.ts file and modify the following:

export class HomeComponent implements OnInit {

  users: Object;

  constructor(private data: DataService) { }

  ngOnInit() { => {
        this.users = data


The first thing you might notice is that we’re placing the code inside of the ngOnInit() function, which is a lifecycle hook for Angular. Any code placed in here will run when the component is loaded.

We’re defining a users property, and then we’re calling the .getUsers() method and subscribing to it. Once the data is received, we’re binding it to our users object and also console.logging it.

Give it a try in the browser and you will see the console shows an object that’s returned. Let’s display it on our home template!

Open up home.component.html and specify the following:


<ul *ngIf="users">
  <li *ngFor="let user of">
    <img [src]="user.avatar">
    <p>{{ user.first_name }} {{ user.last_name }}</p>

Great! Let’s specify some CSS to make this look better in home.component.scss:

ul {
    list-style-type: none;
    margin: 0;padding: 0;

    li {
        background: rgb(238, 238, 238);
        padding: 2em;
        border-radius: 4px;
        margin-bottom: 7px;
        display: grid;
        grid-template-columns: 60px auto;

        p {
            font-weight: bold;
            margin-left: 20px;

        img {
            border-radius: 50%;
            width: 100%;

View the result in the browser:


Angular 7 Forms

If you recall, we generated a component called contact. Let’s create a contact form so that you can learn how to use forms in Angular 7.

Angular 7 provides you with two different approaches to dealing with forms: template driven and reactive forms. I’m not going to go into the differences between these two approaches, but reactive forms generally provide you with more control andform validation can be unit tested as opposed to template driven forms.

To get started, we have to visit the app.module.ts file and import the Reactive Forms Module:

// other imports
import { ReactiveFormsModule } from '@angular/forms';

// other code
  imports: [
    ReactiveFormsModule  // <- Add here

Next, visit the contact.component.ts file and specify the following

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.scss']
export class ContactComponent implements OnInit {

  messageForm: FormGroup;
  submitted = false;
  success = false;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.messageForm ={
      name: ['', Validators.required],
      message: ['', Validators.required]

  onSubmit() {
    this.submitted = true;

    if (this.messageForm.invalid) {

    this.success = true;


First, we’re importing FormBuilder, FormGroup, Validators from @angular/forms.

Then we’re setting a few boolean properties that will help us determine when the form has been submitted and if it validation is successful.

Then we’re creating an instance of the formBuilder in the constructor. We then use this form building to construct our form properties in the ngOnInit() lifecycle hook.

We have two properties, name and message.

Then we created an onSubmit() method that will be called when the user submits the form. This is typically where you would call upon a method in the service to communicate with a mail service of sorts.

Next, visit contact.component.html:

<h1>Contact us</h1>

<form [formGroup]="messageForm" (ngSubmit)="onSubmit()">

    <h5 *ngIf="success">Your form is valid!</h5>

      <input type="text" formControlName="name">
      <div *ngIf="submitted &&" class="error">
        <div *ngIf="">Your name is required</div>

      <textarea formControlName="message"></textarea>
      <div *ngIf="submitted && messageForm.controls.message.errors" class="error">
        <div *ngIf="messageForm.controls.message.errors.required">A message is required</div>

    <input type="submit" value="Send message" class="cta">


  <div *ngIf="submitted" class="results">
    <span>{{ }}</span>

    <span>{{ messageForm.controls.message.value }}</span>

Baked in here is a full form with validation. It also prints out the form values beneath it when the form has been submitted.

Let’s update the css for the component to make it look decent:

label {
    display: block;

    input, textarea {
        display: block;
        width: 50%;
        margin-bottom: 20px;
        padding: 1em;

    .error {
        margin-top: -20px;
        background: yellow;
        padding: .5em;
        display: inline-block;
        font-size: .9em;
        margin-bottom: 20px;

.cta {
    background: #7700FF;
    border: none;
    color: white;

    text-transform: uppercase;
    border-radius: 4px;
    padding: 1em;
    cursor: pointer;
    font-family: 'Montserrat';

.results {
    margin-top: 50px;

    strong {
        display: block;
    span {
        margin-bottom: 20px;
        display: block;

Save it, and the result in the browser should look like this!



As you can see, Angular 7 is quite powerful but we’ve only just scratched the surface. If you’re a beginner, I recommend trying to create a really simple project using what you’ve learned so far and then take it from there.

Learn More

Angular 7 (formerly Angular 2) - The Complete Guide

Learn and Understand AngularJS

Angular Crash Course for Busy Developers

The Complete Angular Course: Beginner to Advanced

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

Become a JavaScript developer - Learn (React, Node,Angular)

Angular (Full App) with Angular Material, Angularfire & NgRx

The Web Developer Bootcamp