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!
Just add the Output decorator before your EventEmitter object and you should be good to go:
@Output() update: EventEmitter<any>;
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);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With