Add ChatComponent

Now go back to our app. Let's add a Chat Dialog Component.

First, we need define the interface of the Message:

src/app/chat/models/chat.model.ts

export interface Message {
  _id: string,
  channelId: string,
  userId: string,
  userName?: string,
  content: string,
  timestamp: Date
}

src/app/chat/components/chat.component.ts

import { Component } from '@angular/core'

import { Message } from '../models/chat.model';

@Component({
  selector: 'my-chat',
  styles: [`
    .name {
      font-weight: bold;
    }

    .timestamp {
      color: #AAAAAA;
    }
  `],
  template: `
    <ul>
      <li *ngFor="let message of messages">
        <p><span class="name">{{message.userName}}</span> <span class="timestamp">{{message.timestamp}}</span></p>
        <p>{{message.content}}</p>
      </li>
    </ul>
  `,
})
export class ChatComponent {
  messages: Message[] = [
    { _id: '0', channelId: '0', userId: '0', userName: 'Jack', content: 'Hello!', timestamp: new Date() },
    { _id: '1', channelId: '0', userId: '0', userName: 'Jack', content: 'Hi!', timestamp: new Date() },
    { _id: '2', channelId: '1', userId: '0', userName: 'Jack', content: 'Hi again!', timestamp: new Date() }
  ];
}

*ngFor is Angular 2's "repeater" directive. Its presence on the <li> tag marks that <li> element and its children as the "repeater template".

We also need add ChatComponent in the declarations of

src/app/app.module.ts

// ...
import { ChatComponent } from './chat/components/chat.component';

@NgModule({
  // ...
  declarations: [
    // ...
    ChatComponent
  ],
  // ...
})
export class AppModule {}

Now we can add <my-chat></my-chat> in our root app component.

src/app/app.component.ts

import { Component } from '@angular/core'

@Component({
  selector: 'app-root',
  template: `
    <my-chat></my-chat>
  `,
})
export class AppComponent {
}

Your app should look like this now:


Run the live example for this part.

results matching ""

    No results matching ""