Blog>
Snippets

Real-Time Form Collaboration

Code an Angular form that multiple users can edit simultaneously. Form changes are broadcast via WebSocket to all users in real time.
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { WebsocketService } from './websocket.service';

@Injectable({
  providedIn: 'root'
})
export class FormSyncService {
  private formUpdates = new Subject<any>();
  public formUpdates$: Observable<any> = this.formUpdates.asObservable();

  constructor(private websocketService: WebsocketService) {
    this.websocketService.connect('ws://your-websocket-endpoint').subscribe(
      (data) => {
        this.formUpdates.next(data);
      }
    );
  }

  sendFormUpdate(data: any) {
    this.websocketService.send(JSON.stringify(data));
  }
}
This Angular service uses a WebsocketService to send and receive form data updates.
import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { FormSyncService } from './form-sync.service';

@Component({
  selector: 'app-collaborative-form',
  template: `
    <form [formGroup]="collabForm" (ngSubmit)="onSubmit()">
      <input
        type="text"
        formControlName="field1"
        (change)="onFieldChange('field1', $event.target.value)"
      />
      <!-- Add more form fields as needed -->
      <button type="submit">Submit</button>
    </form>
  `
})
export class CollaborativeFormComponent {
  collabForm: FormGroup;

  constructor(private fb: FormBuilder, private formSyncService: FormSyncService) {
    this.collabForm = this.fb.group({
      field1: '',
      // Add more form controls as needed
    });

    this.formSyncService.formUpdates$.subscribe((data) => this.applyFormUpdates(data));
  }

  onFieldChange(fieldName: string, value: any) {
    this.formSyncService.sendFormUpdate({ [fieldName]: value });
  }

  applyFormUpdates(data: any) {
    this.collabForm.patchValue(data, { emitEvent: false });
  }

  onSubmit() {
    console.log(this.collabForm.value);
  }
}
This Angular component sets up a collaborative form and subscribes to form changes using the FormSyncService. Changes to form fields are sent to the WebSocket server.
import { Injectable } from '@angular/core';
import { Observable, Observer } from 'rxjs';
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {
  private socket: WebSocketSubject<any>;

  constructor() {}

  connect(url: string): Observable<any> {
    if (!this.socket || this.socket.closed) {
      this.socket = webSocket({ url, deserializer: e => JSON.parse(e.data) });
    }
    return this.socket.asObservable();
  }

  send(data: any) {
    if (this.socket) {
      this.socket.next(data);
    }
  }
}
This Angular service handles the WebSocket connection, including sending and receiving messages.