Previous page: Create and POST a new message using a GraphQL Mutation
Send Data with Angular Form Components
Create an Angular component to send a message to the GraphQL API
Our GraphQL mutation is ready for client integration. We can now build the user interface to send an anonymous user message to our GraphQL API, which will forward the request on to the Slack API. We will then be able to see new message(s) created by our Angular app in the browser.
Describe the mutation
First we need to describe the mutation to Apollo, just as we did for our query.
Open the file web-app/src/app/messages/message.model.ts and add the
following interfaces at the bottom of the file:
// Existing code...
export interface CreateMessageData {
createMessage: ConversationMessage | null;
}
export interface CreateMessageVariables {
text: string;
}
Then open web-app/src/app/messages/messages.operations.ts, import the new
types and add the CREATE_MESSAGE operation at the bottom of the file:
import {
CreateMessageData, // <-- Add new imports
CreateMessageVariables,
// Existing code...
} from './message.model';
// Existing code...
export const CREATE_MESSAGE = gql<CreateMessageData, CreateMessageVariables>`
mutation CreateMessage($text: String) {
createMessage(text: $text) {
...ConversationMessage
}
}
${CONVERSATION_MESSAGE_FRAGMENT}
`;
This defines the mutation CreateMessage with a $text variable that is
passed to the createMessage mutation in our API. Passing the message as a
variable (instead of building it into the query string) means Apollo sends
the text separately from the query, so special characters in a message such
as quotes can't break the request. The fragment that we previously used
to define a message body in the query is reused here with ...ConversationMessage.
Send the mutation from our data service
Open the file web-app/src/app/messages/messages-data.ts. We'll add a
sendMessage method to our service, along with a private method that adds a
message to Apollo's cache.
import { Injectable, inject } from '@angular/core';
import { ApolloCache } from '@apollo/client'; // <-- Add new import
import { Apollo } from 'apollo-angular';
import { ConversationMessage } from './message.model'; // <-- Add new import
import { CREATE_MESSAGE, GET_MESSAGES, MESSAGES_MAX } from './messages.operations'; // <-- Add CREATE_MESSAGE
@Injectable({ providedIn: 'root' })
export class MessagesData {
private readonly apollo = inject(Apollo);
watchMessages() {
// Existing code...
}
sendMessage(text: string) { // <-- Add new method
return this.apollo.mutate({
mutation: CREATE_MESSAGE,
variables: { text },
update: (cache, { data }) => {
if (data?.createMessage) {
this.appendMessage(cache, data.createMessage);
}
},
});
}
/**
* Messages can arrive from both the mutation response and (later) the subscription, so ignore ones already cached.
* The server returns the newest message first.
*/
private appendMessage(cache: ApolloCache, message: ConversationMessage) { // <-- Add new method
const query = { query: GET_MESSAGES, variables: { max: MESSAGES_MAX } };
const messages = cache.readQuery(query)?.messages ?? [];
const { id } = message;
if (!id || messages.some((cached) => cached?.id === id)) {
return;
}
cache.writeQuery({ ...query, data: { messages: [message, ...messages] } });
}
}
The mutate method sends our CreateMessage mutation to the API. It returns an
observable, which only sends the request once something subscribes to it. We
will do that in our component.
Apollo's cache already holds the list of messages that we loaded with our
GetMessages query, and it doesn't know that our mutation has added a new one.
The update function runs when the mutation's response arrives and gives us
the chance to fix that. We read the cached messages with readQuery, put the new
message at the front of the list (the server returns the newest message first) and
save it with writeQuery. Because our message list in the ViewConversation
component is watching this cached query, it updates by itself and the new
message appears immediately, with no page refresh.
We also skip messages whose id is already in the cache. This will matter in
the next parts of this tutorial, where the same message can arrive both from
the mutation response and from a subscription.
Create the text field Angular component
We'll first look at the Typescript component we'll use to send a message.
We will use Angular's
Signal Forms
to manage the text field. In a Signal Form, the value of the form is held in an
ordinary signal (called the model) and we create a form from it with the form
function. Then we create a sendMessage method responsible for sending the
message to our API.
From your project folder, open the
web-app/src/app/messages/create-message/create-message.ts file
and replace the contents with the following code:
import { Component, inject, signal } from '@angular/core';
import { FormField, form, required, submit } from '@angular/forms/signals';
import { firstValueFrom } from 'rxjs';
import { MessagesData } from '../messages-data';
@Component({
selector: 'app-create-message',
imports: [FormField],
templateUrl: './create-message.html',
styleUrl: './create-message.scss',
})
export class CreateMessage {
private readonly messagesData = inject(MessagesData);
protected readonly messageModel = signal({ text: '' });
protected readonly messageForm = form(this.messageModel, (path) => {
required(path.text);
});
protected sendMessage(event: Event) {
event.preventDefault();
submit(this.messageForm, async () => {
const text = this.messageModel().text.trim();
if (!text) {
return;
}
this.messageForm().reset({ text: '' });
await firstValueFrom(this.messagesData.sendMessage(text));
});
}
}
The structure of this component should look familiar. After the imports, we have
metadata in the Component decorator to describe the location of compile-time
assets and the selector name. The FormField directive is what lets our
template connect a form control to the form.
At the top of the class CreateMessage we inject our MessagesData service.
The messageModel signal holds the value of the form, which is an object with a
text property for the user-typed message. We create the messageForm from this
model with Angular's signal form(). The function we pass as the second argument
describes the validation rules: required(path.text) marks the text field as
required. Read more about
Angular's signal forms.
The sendMessage method is called when a user indicates that they've
finished typing and want to send the message. Calling event.preventDefault()
stops the default event firing and propagating so the browser doesn't reload
the page or insert a new line, then hands over to submit, which runs our
function when the form is submitted. The function has a guard that stops an
empty message getting sent. If a message isn't empty, it instantly resets the
text field whilst the message is being sent.
Finally we make a call to the GraphQL API through our service.
sendMessage returns an observable, so we can use firstValueFrom to turn it
into a promise that we can await, which will subscribe to the observable and
sends the mutation.
Create the HTML template for writing a message
We have the behaviour of our component all ready to go, lets now create the layout of our text field and bind it to our component.
From the same folder, open the file: create-message.html and
replace the contents with the following code.
<form class="messages-create-message" (submit)="sendMessage($event)">
<label class="visually-hidden" for="create-message-input">Message</label>
<textarea
id="create-message-input"
class="messages-create-message__input"
[formField]="messageForm.text"
(keydown.enter)="sendMessage($event)"
></textarea>
<button type="submit" class="messages-create-message__send">Send message</button>
</form>
Again, we've used BEM to style the component and determine our class
structure. And also added a textarea form control that is bound to the
text field of our form with the syntax [formField]="messageForm.text".
This binding keeps the textarea and the form in sync in both directions. When
the user types in the text field, the form's value is updated, and when the
component changes the form's value, the words in the textarea are updated as a
result of the component's behaviour. This allows the code
this.messageForm().reset({ text: '' }) within the sendMessage method to
delete all the words that a user has entered so they can start typing a new
message.
We use
event binding
(keydown.enter)="sendMessage($event)", which will call
the sendMessage method when a user hits the 'enter' key. Because sendMessage
prevents the default action of the event, this also stops the enter key adding a
new line to the text field.
As well as typing 'enter', a user can also click the 'Send message' button,
which submits the form and calls the same method through the (submit) event
binding on the form element.
We have also added a label for the textarea so that screen readers can announce
what the field is for. We don't want it to be visible, so it uses a
visually-hidden class. Open the global styles file web-app/src/styles.scss and
add the following to the end of the file:
// Existing code...
.visually-hidden {
position : absolute;
width : 1px;
height : 1px;
padding : 0;
margin : -1px;
overflow : hidden;
clip-path : inset(50%);
white-space : nowrap;
border : 0;
}
This is a common technique that hides content from the screen, but keeps it available to assistive technology. It is in the global stylesheet because it's a generic style that we may want to reuse it in other components.
Create the styles for the text field and button
To complete our component, we just need to add the styles. Within the same
folder, Open the file create-message.scss and add the following:
.messages-create-message {
padding : .5rem .5rem 1rem .5rem;
background-color : #f5f5f5;
* {
box-sizing: border-box;
font-size : 1rem;
font-family: 'Helvetica Neue', Arial;
}
&__input {
min-height : 5rem;
width : 100%;
padding : .6rem;
border-radius : 5px;
border : 1px solid #999;
&:focus,
&:active {
border-color : #004586;
outline : none;
box-shadow: 0 0 0 3px #0385ff;
}
}
&__send {
margin-top : .5rem;
padding : .6rem 1rem;
font-size : 1.2rem;
font-weight : normal;
color : #fff;
background-color : #0070c0;
border : none;
border-radius : 3px;
cursor : pointer;
}
}
That's everything we need to send a message from the application!
Navigate to the Angular application in your browser, type a message in the new component and send. When you refresh the page, you should see your messages at the bottom of the list. It will also appear in systems notifications that have been enabled from any downloaded Slack apps you might have installed for your laptop or mobile phone when logged in to the same Slack workspace.
Note: The application is setup to show a maximum of 4 messages at a time when
it first loads. This can be changed with the MESSAGES_MAX constant defined in
messages.operations.ts.
At the moment we have to refresh the browser window in order to see new messages that anyone else created, lets fix that by using a subscription.
Next, create a GraphQL Subscription to update the Angular app in real time
Previous page: Create and POST a new message using a GraphQL Mutation