First of all, you have no connection between two components or maybe something is not correct in your code. If you have parent/child scenario you can use @Input,@Output
of angular2. If you don't have parent/child scenario you can go with EventEmitter,SharedService
of angular2.
Working demo-EventEmitter way
I have considered AppComponent
is a parentComponent and MainComponent as a child component. Using SharedService & EventEmitter
concepts of angular2
, I'm able to hide AppComponent's
part of view by clicking a button which belongs to 'MainComponent's' view.
AppComponent.ts
import {Component,bind,CORE_DIRECTIVES,OnInit} from 'angular2/core';
import {MainComponent} from 'src/MainComponent';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'my-app',
directives:[MainComponent],
template: `<h1>AppComponent {{onMain}}</h1>
<div *ngIf="onMain == false">
Hello
<br> __________________________________<br>
</div>
<main-app></main-app>
`
})
export class AppComponent implements OnInit {
onMain: Boolean;
constructor(ss: SharedService) {
this.onMain = false;
this.ss = ss;
}
ngOnInit() {
this.subscription = this.ss.getEmittedValue()
.subscribe(item => this.onMain=item);
}
}
MainComponent.ts
import {Component,bind,CORE_DIRECTIVES} from 'angular2/core';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'main-app',
template: `<h1> MainComponent</h1>
<button (click)="changeName()">Change Name</button>
`
})
export class MainComponent {
constructor(ss: SharedService) {
this.ss = ss;
}
changeName() {
this.ss.change();
}
}
shared.service.ts
import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core'
@Injectable()
export class SharedService {
@Output() fire: EventEmitter<any> = new EventEmitter();
constructor() {
console.log('shared service started');
}
change() {
console.log('change started');
this.fire.emit(true);
}
getEmittedValue() {
return this.fire;
}
}