Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 - Trigger event in directive from component

I am trying to trigger an event in a directive used by a component using the EventEmitter.

Component:

@Component({
    selector: 'messages',
    templateUrl: 'static/pages/messages/messages.component.html',
    directives: [AutoScroll],
    events: ['update'],
    providers: [
        HTTP_PROVIDERS,
        RoomService,
    ],
    styleUrls: ['../static/css/messages.component.css', '../static/css/app.component.css']
})

export class MessagesComponent {

    public selectedRoom: Room = <Room>{};

    @Output()
    public update: EventEmitter;

    constructor (private _roomService: RoomService) {
        this.update = new EventEmitter();
    }

    public postMessage (msg) {

        this.update.next({});

        this._roomService.postMessage(msg)
            .subscribe(res => {
                this.selectedRoom.messages.push(res);
            });
    }
}

HTML-template:

<auto-scroll class="chat-messages" (update)="onUpdate($event)">
    <div class="chat-message" *ngFor="#message of selectedRoom.messages">
        <div class="message-content">
            {{ message.text }}
        </div>
    </div>
</auto-scroll>

Directive:

@Directive({
    selector: 'auto-scroll',
    template: '<div></div>'
})
export class AutoScroll {

    constructor (private el: ElementRef) {}

    public onUpdate(event) {
        console.log('Updated');
    }
}

Basically what I want to do is to trigger an event in the auto-scroll directive every time a new message is posted. I have gotten this to work between two components, but not between a component and a directive.

I am quite new at Angular 2, but I hope that you get a clear picture of what I want to achieve!

like image 574
Valdemar Edvard Sandal Rolfsen Avatar asked Apr 17 '16 09:04

Valdemar Edvard Sandal Rolfsen


2 Answers

Just add the Output decorator before your EventEmitter object and you should be good to go:

@Output() update: EventEmitter<any>;
like image 83
Mush Avatar answered Nov 11 '22 15:11

Mush


In your specific case EventEmitter does not help since AutoScroll is used inside of MessagesComponent template.

You could implement it like this:

export class MessagesComponent {

    public selectedRoom: Room = <Room>{};

    @ViewChild(AutoScroll)
    public scroller: AutoScroll;

    constructor (private _roomService: RoomService) {

    }

    public postMessage (msg) {

        this._roomService.postMessage(msg)
            .subscribe(res => {
                this.selectedRoom.messages.push(res);
                this.scroller.onUpdate(msg);
            });
    }
}
like image 26
kemsky Avatar answered Nov 11 '22 16:11

kemsky