简体   繁体   中英

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!

只需在您的EventEmitter对象之前添加Output装饰器,就可以了:

@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);
            });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM