In my angularjs project, I am facing an issue with click from the html. My code module is as follows I have a header module and an auth module
import { Component } from '@angular/core';
@Component({
selector: 'layout-header',
templateUrl: './header.component.html'
})
export class HeaderComponent {
constructor() {}
}
In header.component.html I have added a click event, my intention is to call a function from other component click code is as follow
<ul>
<li class="nav-item"><a class="nav-link" (click)="clickLogout($event)" routerLinkActive="active"> Logout </a> </li>
</ul>
"clickLogout" function is added on other component any if does'nt calling up If I add the same "clickLogout" in header.component.ts, it works.
But for some reason I need it on another component, So is there any option to trigger click of other component from view : (click)="clickLogout($event)"
I am using angularjs4, Somebody please advice!
Directory structure is as follows
app
--auth
----auth-logout.component.ts
--shared
----layout
-------header.component.ts
-------header.component.html
I need the click call on auth-logout.component.ts
You Need a shared service to do so :
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MessageService {
private subject = new Subject<any>();
logout() {
this.subject.next({ text: 'logout'});
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
and in header component :
import { Component } from '@angular/core';
import { MessageService} from 'service/MessageService'; //import service here as per your directory
@Component({
selector: 'layout-header',
templateUrl: './header.component.html'
})
export class HeaderComponent {
constructor(private messageService: MessageService) {}
clickLogout(): void {
// send message to subscribers via observable subject
this.messageService.logout();
}
}
And in any other component EDIT:
import { Component } from '@angular/core';
import { Subscription } from 'rxjs/Subscription'; //Edit
import { MessageService} from 'service/MessageService'; //import service here as per your directory
@Component({
selector: 'another-component',
templateUrl: './another.component.html'
})
export class AnotherComponent {
constructor(private messageService: MessageService) {
// subscribe to home component messages
this.messageService.getMessage().subscribe(message => {
//do your logout stuff here
});
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}
Reference taken from here.