Sending group messages

Now, let's implement some support so that we can send messages to particular groups:

  1. Import FormsModule into the main application module:
      import { FormsModule } from '@angular/forms';

You are going to need it later to establish two-way binding to the message's text.

  1. Let's introduce the message editor. Append the following code to the messages.component.html template:
      <div class="message-editor">
<mat-form-field class="message-editor-field">
<input
[(ngModel)]="newMessage"
matInput
placeholder="Message the group"
autocomplete="off"
(keyup.enter)="send()"
/>
</mat-form-field>
</div>

Here, we are binding the input element to the newMessage property in a two-way fashion, and we're also handling the keyup.enter event by calling the send() function. We'll come back to these later in this section.

In terms of styling, I suggest at least stretching the input element horizontally so that it takes up all the available space.

  1. Update the messages.component.scss file so that it matches the following code:
      .message-editor {
padding: 0 10px;

.message-editor-field {
width: 100%;
}
}
  1. Finally, we need to handle the Enter key being pressed and send the message to the server. The AngularFire library makes this whole process trivial. Switch to messages.component.ts and update the code according to the following listing:
      @Component({...})
export class MessagesComponent implements OnInit {
newMessage = '';
// ...

send() {
if (this.newMessage) {
const messages = this.firebase.list('messages');

messages.push({
group: this.group,
text: this.newMessage
});

this.newMessage = '';
}
}
}
  1. We take the newMessage value and use it with group to compose and send the JSON object to the /messages list. Let's see how this works in practice. Switch to the application and write a message, like so:

  1. Now, press the Enter key and ensure that the message is erased from the input element. At the same time, because of the Firebase Realtime Database, our message list is updated from the server:

  1. If you check the Firebase console, it should contain a new entry:

Try moving to another group and leaving the message there, too. Note that you only see the messages that correspond to the selected group.

I suggest that we move on and update the user interface so that it's more friendly for our users.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset