How To Build A Virtual Event Site With Angular (Youtube-Live Clone)
Tags: youtube, events, cometchat, angular
Published: 2021-05-13 21:44:10

What you’ll be building. [Demo](https://clone-6fd6f.web.app/), Git Repo [Here](https://github.com/Daltonic/youtube-live-clone).

![Youtube-Live Clone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jv71b6iu4sx0g894s6dg.gif)
<figcaption>Youtube-Live Clone</figcaption>


#### Introduction

There is a real principle in life that states: "If you want to be great, then start by doing great things in little ways". This also applies to you as a developer aspiring to influence the industry in a great way, "You can start by building great things in a little way". One way to build great things is by starting small. And the [cometchat](https://www.cometchat.com/) communication SDK offers you the opportunity to integrate some great messaging features into your apps such as text, audio, and video chatting features.


#### Prerequisites

To follow this tutorial, you must have a basic understanding of the general principles of [Angular](https://angular.io/). This will help you to speedily digest this tutorial.


#### Installing The App Dependencies

First, you need to have NodeJs installed on your machine, you can go to their [website](https://nodejs.org/) to do that.

Second, you need to also have the Angular-CLI installed on your computer using the command below.

```sh
npm install -g @angular/cli
```

Next, create a new project with the name youtube-live-clone.

```sh
ng new youtube-live-clone
```

The `ng new` command prompts you for information about features to include in the initial app. Accept the defaults by pressing the Enter or Return key.

The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a few minutes.

Last, install these essential dependencies for our project using the command below.

```sh
ng add @angular/material
npm install @angular/youtube-player
npm install @angular/fire
ng add @angular/fire
```

Now that we're done with the installations, let's move on to building our youtube-live clone solution.


#### Installing Comet Chat SDK

1. Head to CometChat Pro and create an account.
2. From the dashboard, add a new app called "youtube-clone".
3. Select this newly added app from the list.
4. From the Quick Start copy the APP_ID, REGION and AUTH_KEY. These will be used later.
5. Navigate to the Users tab, and delete all the default users and groups leaving it clean (very important).
6. Get the Angular CLI installed on your machine by entering this command on your terminal. `npm install -g @angular/cli`
7. Open the "environment.ts" file in the project.
8. Enter your secret keys from comet Chat and Firebase below on the next heading.
9. Copy the same settings into the "environment.prod.ts" as well.
10. Run the following command to install the comet chat SDK.

```sh
npm install @cometchat-pro/chat@2.3.0 --save
```


#### The Environment Variables

The setup below spells out the format for configuring the environment.ts files for this project.

```sh

firebase: {
    apiKey: 'xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx',
    authDomain: 'xxx-xxx-xxx-xxx-xxx-xxx-xxx',
    databaseURL: 'xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx',
    projectId: 'xxx-xxx-xxx',
    storageBucket: 'xxx-xxx-xxx-xxx-xxx',
    messagingSenderId: 'xxx-xxx-xxx',
    appId: 'xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx',
    measurementId: 'xxx-xxx-xxx',
  },
  APP_ID: 'xxx-xxx-xxx',
  AUTH_KEY: 'xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx',
  APP_REGION: 'xx',
```


#### Setting Up Firebase Project

Head to Firebase create a new project and activate the email and password authentication service. This is how you do it.

To begin using Firebase, you’ll need a Gmail account. Head over to Firebase and create a new project.

![Firebase Console Create Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8i1l211jn25943mtl2z.png)
<figcaption>Firebase Console Create Project</figcaption>

Firebase provides support for authentication using different providers. For example Social Auth, phone numbers as well as the standard email and password method. Since we’ll be using the email and password authentication method in this tutorial, we need to enable this method for the project we created in Firebase, as it is by default disabled.

Under the authentication tab for your project, click the sign-in method and you should see a list of providers Firebase currently supports.

![Firebase Authentication Options](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5dmnx5ckfuqt4fa0gt9.png)
<figcaption>Firebase Authentication Options</figcaption>

Next, click the edit icon on the email/password provider and enable it.

![Firebase Enabling Authentication](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7dkr0ddis55pybi08n7.png)
<figcaption>Firebase Enabling Authentication</figcaption>

Next, you need to go and register your application under your Firebase project. On the project’s overview page, select the add app option and pick web as the platform.

![Youtube-Live Clone Project Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i6q6pvwwks2sdcdrqos1.png)
<figcaption>Youtube-Live Clone Project Page</figcaption>

Once you’re done registering the application, you’ll be presented with a screen containing your application credentials. Take note of the second script tag as we’ll be using it shortly in our Angular application.

Congratulations, now that you're done with the installations, let's do some configurations.


#### Configuring Comet Chat SDK

Inside your project structure, open the `main.ts` and paste these codes.

{% gist https://gist.github.com/Daltonic/88e612d82a5e6824278629be3bdbd927 %}

<figcaption>The main.ts file</figcaption>

The above codes initialize comet chat in your app and before our app starts up. The main.ts entry file uses your comet chat API Credentials. The `environment.ts` file also contains your Firebase Configurations variable file. Please do not share your secret keys on Github.


#### Setting Up The Router

The `app-routing.module.ts` file has all the routes available in our app along with their security clearance.

{% gist https://gist.github.com/Daltonic/06a3d33ba5e11e8126383fb6a557b9ef %}

<figcaption>The App Routing Module file</figcaption>


#### Project Structure

The image below reveals the project structure. Make sure you see the folder arrangement before proceeding.

![Youtube-Live Clone Project Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lu3jsa3h2dcs8fqu7vxy.png)
<figcaption>Youtube-Live Clone Project Structure</figcaption>

Now let's make the rest of the project components as seen in the image above.


#### The App Component

The following code is a wrapper around our app within the `angular-router` enabling swift navigation. For each route, this component navigates our app to the appropriate URL.

{% gist https://gist.github.com/Daltonic/3b3db03466b14cf3e90255f0926a24cd %}
<figcaption>The app.component.ts file</figcaption>

Replace everything in the `app.component.html` file with `<router-outlet></router-outlet>` and remove every style from the `app.component.css`.


#### The Angular Material Icons Setup

The following code will configure our app to harness the full power of material icons throughout our project.

{% gist https://gist.github.com/Daltonic/916269efa086cb0f87c12efd9b32a879 %}
<figcaption>The angular-material.module.ts file</figcaption>


#### The App Module

Paste the codes in your `app.module.ts file`, this is a very important file that bundles all the components we will be using for our project.

{% gist https://gist.github.com/Daltonic/c3f87fdc602cb60cd78a3caccd7d913a %}
<figcaption>The app.module.ts</figcaption>

#### The Sidebar Component

![The Sidebar component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9rjm29bqhvizj79b01f0.png)
<figcaption>The Sidebar component</figcaption>

The sidebar component, beautifully crafted with sub-components mirrors the routes of the real **YouTube live**. You must get to study the markup and styling structure on your own time. This component is reused across two other components in our app. Here is the code that sponsors its operation.


{% gist https://gist.github.com/Daltonic/f25c6423b72f16b3908c0324b8b2026d %}
<figcaption>The Sidebar Component</figcaption>


#### The Header Component

![The Header component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6cfnskb2qhdhrn3hr12b.png)
<figcaption>The Header component</figcaption>

The header component, this single-file reusable component carries a bulk of vital features necessary for the functioning of our application. Besides being the navigational agent of our app, it also houses the search-bar component responsible for sorting out relevant events for the user. No big words, here are the codes responsible for its action.

{% gist https://gist.github.com/Daltonic/edac9f36dde54e8719efbd9424326097 %}
<figcaption>The Header Component file</figcaption>

#### The Video Components

![The Video component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29yei6faxadg4537k9mh.png)
<figcaption>The Video component</figcaption>

This is a single-file component used across the app for listing events retrieved from firestore. It carries event information such as the title, description, image URL, and YouTube link. The success of this app owes a big thanks to this very component. The codes below clearly describe the functionality of this component.

{% gist https://gist.github.com/Daltonic/00dd4d3cce5558d6da37950724d4c315 %}
<figcaption>The Video Card component</figcaption>

#### The Related Video Component

![The Related Video Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/locmmd2vj3vodvvg1fm5.png)
<figcaption>The Related Video Component</figcaption>

Like the `video.component.ts`, this component acts similarly. The only difference is that, while the video components list videos vertically, this component list videos horizontally. Here are the codes for that.

{% gist https://gist.github.com/Daltonic/6128e493935d7a480589f0b446e2b247 %}
<figcaption>The Related Videos component</figcaption>


#### The Rows Video Component

![The Rows Video Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llfs2cphefdu1laz6pln.png)
<figcaption>The Rows Video Component</figcaption>

This component is responsible for making the sidebar routes look like the image above. It takes an Angular-Material Icon and a title to display what you see above. Below is the code for it.

{% gist https://gist.github.com/Daltonic/4ddf9095a624d6432384b02cf3878fc4 %}
<figcaption>The Rows Video Component</figcaption>

#### The Registration Component

![The Registration Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t7s3zgcmgd7uefjilcru.png)
<figcaption>The Registration Component</figcaption>

This component combines the power of firebase auth-service and comet chat such that whenever a new user signs up for our app, the user’s details are captured by firebase and also registered on our comet chat account. The code below explains it in detail.

```ts

public submit(form: any): void {
    this.loading = true;
    const fullname = form.fullname;
    const email = form.email;
    const password = form.password;
    const avatar = this.generateImageFromIntial(fullname);

    this.auth
      .createUserWithEmailAndPassword(email, password)
      .then((res) => {
        res.user
          .updateProfile({
            displayName: fullname,
            photoURL: avatar,
          })
          .then(() => this.signUpWithCometChat({ ...res.user, avatar }));
      })
      .catch((error) => {
        console.log(error);
        this.loading = false;
      });
  }
  private signUpWithCometChat(data: any) {
    const apiKey = environment.APP_KEY;
    const user = new CometChat.User(data.uid);
    user.setName(data.displayName);
    user.setMetadata({avatar: data.avatar});
    CometChat.createUser(user, apiKey)
      .then(() => this.route.navigate(['login']))
      .catch((error) => {
        console.log(error);
        this.loading = false;
      });
  }
```

So, whenever a user registers in our app, automatically, he is simultaneously registered on our comet chat account. Here is the full code that explains it all.

{% gist https://gist.github.com/Daltonic/d95c44f3cb8cc489b1cf05b19cecd237 %}
<figcaption>The Registration Component TypeScript File</figcaption>

{% gist https://gist.github.com/Daltonic/8fee6fbbb45e47c559a02e851d72cd22 %}
<figcaption>The Registration Component HTML file</figcaption>

{% gist https://gist.github.com/Daltonic/83179fd0b6afc2ee02e6bed5691b8772 %}
<figcaption>The Registration Component CSS file</figcaption>


#### The Login Component

![The Login Componentt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5d8bp16isp028iulmqsx.png)
<figcaption>The Login Component</figcaption>

Apart from being gorgeously styled, the Login component follows the behavior of the Registration component. For example, if a user named Maxwell registered on our app, he is then navigated to the login page to sign in. Because comet chat also has his details, the moment he signs in, he will also be signed in by comet chat. The piece of code below demonstrates this process better.

```ts

public submit(form): void {
    this.loading = true;
    const email = form.email;
    const password = form.password;
    this.auth
      .signInWithEmailAndPassword(email, password)
      .then((res) => this.loginCometChat(res.user))
      .catch((error) => {
        console.log(error);
        this.loading = false;
      });
  }
  private loginCometChat(user: any) {
    const apiKey = environment.APP_KEY;
    CometChat.login(user.uid, apiKey)
      .then(() => this.route.navigate(['']))
      .catch((error) => {
        console.log(error);
        this.loading = false;
      });
  }
```

Once a user is successfully logged in, he is then redirected to the home page. The `route-guard` within the `app.routing-module.ts` ensures that only authenticated users are permitted to access the home page. The following scripts below describes the overall operations of the login component.

{% gist https://gist.github.com/Daltonic/d0db7aec5d70804b46824d8661d29868 %}
<figcaption>The Login Component TypeScipt file</figcaption>

{% gist https://gist.github.com/Daltonic/4c369906463586334fd7d7f982e2504c %}
<figcaption>The Login Component HTML file</figcaption>

{% gist https://gist.github.com/Daltonic/6e0b2eb8bbbb4a2c692640b678e6cbef %}
<figcaption>The Login Component CSS file</figcaption>


#### The Profile Component

![The Profile Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l405bqvh1brfnhf8mkn2.png)
<figcaption>The Profile Component</figcaption>

The profile component is charged with the responsibility of updating our data which will reflect across our app. One of the primary tasks of this component is to change a user's profile.

In the registration component, once a user signs up, we generated a placeholder avatar for him using the initial of his name. The profile component allows a user to update their avatar to their preferred choice. Here is the full code performing this operation.

{% gist https://gist.github.com/Daltonic/235ac04ce643d329c7a733d1c2a34904 %}
<figcaption>The Profile Component TypeScript File</figcaption>

{% gist https://gist.github.com/Daltonic/0279f0984427b992b3d224a443b90e38 %}
<figcaption>The Profile Component HTML File</figcaption>

{% gist https://gist.github.com/Daltonic/4b92252e73a57c435026d317510c0afd %}
<figcaption>The Profile Component CSS File</figcaption>

#### The Create-Event Component

![The Create-Event Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69omdr155vq57vhaw48c.png)
<figcaption>The Create-Event Component</figcaption>

This is a major component with many responsibilities associated with the success of our application. This component retains the duty of collecting an event’s information like the video title, link, image URL, description, and so on. The image above clearly describes it.

You must understand some background activities that are transacted whenever an event is added to our platform.

For instance, a user named Musa adds a new event to our platform, two operations were carried out behind the scene. One, firebase stored the details of that event, and comet chat created a group just for that event as well. The code below explains it better.

```ts

public submit(form: NgForm): void {
    if (form.valid) {
      this.loading = true;
      const data = form.value;
      data.timestamp = new Date().toJSON();
      data.views = this.randomNumber(100, 300);
      data.uid = this.authState.uid;
      this.firestore
        .collection('events')
        .add(data)
        .then((d) => {
          form.reset();
          const groupName = this.toVideoId(data.videoId);
          const guid = d.id;
          this.cometChatCreateGroup({ groupName, guid });
        });
    }
  }
  private cometChatCreateGroup(data: any) {
    const GUID = data.guid;
    const groupName = data.groupName;
    const groupType = CometChat.GROUP_TYPE.PUBLIC;
    const password = '';
    const group = new CometChat.Group(GUID, groupName, groupType, password);
    CometChat.createGroup(group)
      .then((group) => console.log('Group created successfully:', group))
      .catch((error) => {
        console.log('Group creation failed with exception:', error)
        this.loading = false;
      });
  }
```

Now that you understand what is happening under the hood, let’s have a look at the full code of this component.

{% gist https://gist.github.com/Daltonic/810b99f73354ee1fe9bb000b9dbc46b0 %}
<figcaption>The Create-Event TypeScript File</figcaption>

{% gist https://gist.github.com/Daltonic/95bba1d77bba88c96d62276b1234c030 %}
<figcaption>The Create-Event HTML File</figcaption>

{% gist https://gist.github.com/Daltonic/d360c16870575939f17a2aa229fb97c8 %}
<figcaption>The Create-Event CSS File</figcaption>


#### The Edit-Event Component

Like the create-event component, the edit component those almost the same job, only that it modifies the details of the event you added to the platform.

There is an important mode of operation that it does which can be best explained with the code snippets below.

{% gist https://gist.github.com/Daltonic/f12cf4bb01471aa63e138de9adae1a72 %}
<figcaption>The Edit-Event TypeScript File</figcaption>

{% gist https://gist.github.com/Daltonic/a1904d255ca90ba4f52ca5b38f8893f0 %}
<figcaption>The Edit-Event HTML File</figcaption>

{% gist https://gist.github.com/Daltonic/f86c2eef019b6a6fe2df3ebab90e8fa7 %}
<figcaption>The Edit-Event CSS File</figcaption>

#### The Events Component

![The Events Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tfy0i4c2ad9gtly714y5.png)
<figcaption>The Events Component</figcaption>

This is a big-player component in the overall success of our application. Its assignment is to list elegantly all the events we have created in our app.

It employs the services of the video component for vertically rendering video cards to the view. No more talks, let’s see how it functions code-wise.

{% gist https://gist.github.com/Daltonic/7b3fe89f8ed35df9b32baaed46b41b39 %}
<figcaption>The Events Component TypeScript File</figcaption>

{% gist https://gist.github.com/Daltonic/08916f275900ff179227e019826070fa %}
<figcaption>The Events Component HTML File</figcaption>

{% gist https://gist.github.com/Daltonic/90765f4a1f0efd930476342a0f2b77c0 %}
<figcaption>The Events Component CSS File</figcaption>

#### The Event Component

![The Event Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ddyqgfe3ka4atuun63dh.png)
<figcaption>The Event Component</figcaption>

This component may sound similar to the previous component, but they do totally different things. While the events component displays a list of events this component showcases a single event.

Other than the cool design it features, the event component embodies a full catalog of mind-blowing responsibilities, let’s list them.


- Event Video Streaming
- Live-Chatting Activity
- Related Videos Displaying
- Performs Real-Time Messaging
- Event Edit & Delete Abilities

That’s some responsibilities don’t you think so? Allow me to discuss some of the functionalities with you in codes.

```ts

// This method listens for a real-time message and renders it to view
private listenForMessage(guid: string) {
    const listenerID = guid;
    CometChat.addMessageListener(
      listenerID,
      new CometChat.MessageListener({
        onTextMessageReceived: (message) => {
          this.messages.push(message);
          this.scrollToEnd();
        },
      })
    );
  }

// This method retreives all the messages for the current event
private getMessages(guid: string) {
    const limit = 50;
    const messagesRequest = new CometChat.MessagesRequestBuilder()
      .setLimit(limit)
      .setGUID(guid)
      .build();
    messagesRequest
      .fetchPrevious()
      .then((messages: Array<any>) => {
        this.messages = messages.filter((m) => m.type == 'text');
      })
      .catch((error) =>
        console.log('Message fetching failed with error:', error)
      );
  }

// This method sends a new message into the group
private sendMessage(data: any, form: NgForm) {
    const receiverID = data.guid;
    const messageText = data.message;
    const receiverType = CometChat.RECEIVER_TYPE.GROUP;
    const textMessage = new CometChat.TextMessage(
      receiverID,
      messageText,
      receiverType
    );
    CometChat.sendMessage(textMessage)
      .then((message) => {
        this.messages.push(message);
        form.reset();
        this.scrollToEnd();
        this.words = 0;
      })
      .catch((error) =>
        console.log('Message sending failed with error:', error)
      );
  }

ngOnDestroy(): void {
    CometChat.removeMessageListener(this.id)
}

// This method joins a user into a group associated with an event
private joinGroup(guid: string) {
    const GUID = guid;
    const password = '';
    const groupType = CometChat.GROUP_TYPE.PUBLIC;
    CometChat.joinGroup(GUID, groupType, password)
      .then((group) => {
        console.log('Group joined successfully:', group);
        this.router.navigate(['events', guid]);
      })
      .catch((error) => {
        if (error.code != 'ERR_ALREADY_JOINED')
          console.log('Group joining failed with exception:', error);
        this.router.navigate(['events', guid]);
      });
  }
```

Now that you understand the background activities within this component, it’s time you see the full code.

{% gist https://gist.github.com/Daltonic/64cce84e1198d9d8920805dc8cba9ffa %}
<figcaption>The Event Component TypeScript File</figcaption>

{% gist https://gist.github.com/Daltonic/7c48875443aa66bc6bfa9cb52920b6f8 %}
<figcaption>The Event Component HTML File</figcaption>

{% gist https://gist.github.com/Daltonic/02f6e65db72bdb02883ad7a85fcd7ceb %}
<figcaption>The Event Component CSS File</figcaption>

#### The Search Component

![The Search Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xncq3fx9l1bmwywo9a8.png)
<figcaption>The Search Component</figcaption>

Lastly, let’s discuss how the search component resolves events sorting operations. Obviously, as events are added more into the platform, a threshold will come that will require an ability to search for events. This component offers that solution, let’s see the logic behind it in the codes below.

{% gist https://gist.github.com/Daltonic/faf2f8b721de9101ab7bc3a59f2ed160 %}
<figcaption>The Event Component TypeScript File</figcaption>

{% gist https://gist.github.com/Daltonic/ef59c97792eec617be71537dccbeae0f %}
<figcaption>The Event Component HTML File</figcaption>

{% gist https://gist.github.com/Daltonic/a21ff38b2e363f7a0cec2efa56baaaf4 %}
<figcaption>The Event Component CSS File</figcaption>

Once you are done pasting the codes as directed, run the command below to start your application.

```sh
ng serve --open
```

After a few seconds of building in the terminal, your app should be up and running.

Congratulations, you just completed the clone of YouTube-Live, great job!!!


#### Conclusion

In conclusion, building a virtual event site such as YouTube-Live is a fantastic idea to up your development skill. Especially, the integration of a live-chatting feature using the comet chat SDK makes a dream come true for a fellow like me.

This tutorial has educated you with the abilities needed to pull together a clone of one of the most valuable applications of our time. It's time to get busy and replicate a YouTube-Live Clone.