[英]angular2 - Trigger event in directive from component
I am trying to trigger an event in a directive used by a component using the EventEmitter. 我正在尝试使用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: 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: 指示:
@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. 基本上,我想做的是每次发布新消息时在auto-scroll指令中触发一个事件。 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! 我在Angular 2上还很陌生,但是我希望您能清楚地了解我想要实现的目标!
只需在您的EventEmitter对象之前添加Output装饰器,就可以了:
@Output() update: EventEmitter<any>;
In your specific case EventEmitter
does not help since AutoScroll
is used inside of MessagesComponent
template. 在您的特定情况下, EventEmitter
没有帮助,因为在MessagesComponent
模板内部使用了AutoScroll
。
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);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.