我试图在使用EventEmitter的组件使用的指令中触发事件。
组件:
@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模板:
<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({
selector: 'auto-scroll',
template: '<div></div>'
})
export class AutoScroll {
constructor (private el: ElementRef) {}
public onUpdate(event) {
console.log('Updated');
}
}
基本上我想要做的是每次发布新消息时在自动滚动指令中触发一个事件。我已经让它在两个组件之间工作,但不是在组件和指令之间。
我在Angular 2上很新,但我希望你能清楚地了解我想要实现的目标!
答案 0 :(得分:4)
只需在EventEmitter对象之前添加Output装饰器,你就应该好了:
@Output() update: EventEmitter<any>;
答案 1 :(得分:1)
在您的特定情况下EventEmitter
无效,因为在AutoScroll
模板中使用了MessagesComponent
。
你可以像这样实现它:
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);
});
}
}