Angular 2: emitter listener between components

Viewed 10626

I am making a 'skip to content' link. The link is in app.component and the content is in login.component, along with the target.

I've tried several methods, none of which worked out. So now I'm trying emitter/listener:

app.component (emitter):

import { Component, Output, EventEmitter} from '@angular/core';

export class AppComponent {

    @Output() skipToCtrl: EventEmitter<any> = new EventEmitter();

    skipLink() {
        this.skipToCtrl.emit();
    }
}

<a href="#content-start" (click)="skipLink()">Skip to main content</a>

login.component (listener):

<input type="text" #firstControl name="username" />

Don't know how login can subscribe to the event from within login. I keep finding articles that say not to do it How to subscribe to an event on a service in Angular2? but no articles that describe how to do it.

4 Answers

100% Working!!!! It's basically a patch using Javascript:

Make a hidden input element in which component(app.component in your case) you need to call

<input type="hidden" id="getdata" (click)="Mydata();">

Here Mydata will be function in app.component

And call/Click this from other component(Login) using javascript:

document.getElementById('getdata').click();
Related