Chat UI for ionic 3


#1

I’ve created a chat interface whenever I send messages to dialog flow or receive messages from dialog flow they appear on the left side of the screen. I want my messages to be on the right side & dialog flow messages on the left side & both chat bubbles should of different colours. I have no idea how to differentiate them. Can someone help me? This is my HTML code.

<ion-content>
  <div style="font-size:10px; text-align:center;">7 minutes ago</div>
  <div class="msgbubble" *ngFor="let msg of messages">
    <div class="innermsg">
      {{ msg }}
    </div>
  </div>
</ion-content>

<ion-footer>
  <ion-toolbar>
    <ion-input placeholder="Type here" [(ngModel)]="question" type="text"></ion-input>
    <ion-buttons right>
      <button ion-button clear icon-only id="sendicon" (click)="ask(question)">
        <ion-icon name="send"></ion-icon>
      </button>
    </ion-buttons>
  </ion-toolbar>
</ion-footer>

This is ts code.

ask(question) {
    try {
      this.messages.push(question);
      var headers = new Headers();
      headers.append("Accept", 'application/json');
      headers.append('Content-Type', 'application/json' );
      headers.append('Authorization', 'Bearer ' + this.Access_token)
      let options = new RequestOptions({ headers: headers });

      let postParams = {
       "lang": "en",
      "query": question ,
      "sessionId": "12345",
      "timezone": "America/New_York"
      }

      try{
      this.http.post("https://api.dialogflow.com/v1/query?v=20150910", postParams, options)
        .subscribe(data => {
          let obj = JSON.parse(data['_body']);
          this.answer = obj.result.fulfillment.speech;
          //console.log(data['_body']);
          console.log(this.answer);
          this.messages.push(this.answer);

         }, error => {
          console.log(error);// Error getting the data
        });
    }
    catch(e){
      console.log(e);
    }
    }

  catch(e){
    console.log(e);
  }
  }

I want the UI should be as a general chat page/bot. Sending messages on right & receiving messages on left.


#2

You could have something like this:

<div class="innermsg left" *ngIf="currentUserId != msg.userId">
      {{ msg }}
    </div>
<div class="innermsg right" *ngIf="currentUserId == msg.userId">
      {{ msg }}
    </div>

So you would need to pass the user/owner of each message, part of the messages array/object (so {{ msg }} needs to be something like {{ msg.text }} or whatever ) + notice I’ve added left and right class names to style left and right bubbles.

Hope that helps