首先,你有兩個組件之間沒有連接或者也可以是不正確的在你的代碼。如果您有父/子方案,則可以使用angular2的@Input,@Output
。如果您沒有父/母方案,您可以使用angular2的EventEmitter,SharedService
。
Working demo-EventEmitter way
我已經考慮AppComponent
是一個爲父級和MainComponent作爲子組件。通過使用angular2
的SharedService & EventEmitter
概念,我可以通過單擊屬於「MainComponent's」視圖的按鈕來隱藏AppComponent's
視圖的一部分。
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;
}
}
您可以在**服務使用'EventEmitter' **。然後讓AppComponent訂閱它以獲取更改事件。 –