import { Component , Input , OnInit , AfterViewInit , OnDestroy , ElementRef , ViewChild } from '@angular/core' ; import { RoomService , UserService } from '../core' ; import { IMessage , IRoom } from '../../models' ; import { MessageService } from './message.service' ; @ Component ( { selector : 'room' , styleUrls : [ './room.component.scss' ] , templateUrl : './room.component.html' } ) export class RoomComponent implements OnInit , AfterViewInit , OnDestroy { @ ViewChild ( 'scroll' ) private scroll : ElementRef ; @ ViewChild ( 'focus' ) private focus : ElementRef ; @ Input ( ) room : IRoom ; message : string = '' ; messages : IMessage [ ] ; private messageService : MessageService ; private alreadyLeftChannel : boolean = false ; constructor ( private roomService , public userService ) { } ngOnInit ( ) { this . messageService = new MessageService ( this . userService , this . room . name ) ; this . messageService . messages . subscribe ( messages => { this . messages = messages ; setTimeout ( ( ) => { this . scrollToBottom ( ) ; } , 200 ) ; } ) ; } ngAfterViewInit ( ) { this . focus . nativeElement . focus ( ) ; } ngOnDestroy ( ) { if ( ! this . alreadyLeftChannel ) { this . leave ( ) ; } } send ( ) { this . messageService . send ( this . message ) ; this . message = '' ; } leave ( ) { this . alreadyLeftChannel = true ; this . messageService . leave ( ) ; this . roomService . leave ( this . room . name ) ; } scrollToBottom ( ) { try { this . scroll . nativeElement . scrollTop = this . scroll . nativeElement . scrollHeight ; } catch ( error ) { console . log ( 'ERROR:' , error ) ; } } eventHandler ( event ) { if ( event . key === 'Enter' ) { this . send ( ) ; } } }