1.从一个组件调用方法到另一个组件(如果它们不是父子组件),只能使用服务。
//FirstComponent
import {Component} from '@angular/core';
import {CommonService} from './common.service';
@Component({
selector: '<first-component></first-component>',
template: 'some html here',
providers: [CommonService]
})
export class FirstComponent {
constructor(private _service: CommonService) {
this._service.callMethodOfSecondComponent();
}
}
//CommonService
import {Subject} from 'rxjs/Subject';
@Injectable()
export class CommonService {
invokeEvent: Subject<any> = new Subject();
callMethodOfSecondComponent() {
this.invokeEvent.next(someValue)
}
}
//SecondComponent
import {Component, OnInit} from '@angular/core';
import {CommonService} from './common.service';
@Component({
selector: '<second-component></second-component>',
template: 'some html here',
providers: [CommonService]
})
export class SecondComponent {
constructor(private _service: CommonService) {
this._service.invokeEvent.subscribe(value => {
if(value === 'someVal'){
this.callMyMethod();
}
});
}
callMyMethod(){
//code block to run
}
}
2.从子组件调用父组件的方法
//Child Component
import {Component} from '@angular/core';
@Component({
selector: '<child-component></child-component>',
template: 'some html here',
})
export class ChildComponent {
@Output()
emitFunctionOfParent: EventEmitter<any> = new EventEmitter<any>();
constructor() {
}
someMethodOfChildComponent(){
this.emitFunctionOfParent.emit(someValue);
}
}
//ParentComponent
import {Component} from '@angular/core';
@Component({
selector: '<parent-component></parent-component>',
template: `some html
<child-component
(emitFunctionOfParent)="myMethod($event)">
</child-component>
some html
`,
})
export class ParentComponent {
constructor() {
}
myMethod(someValue){
// i am called
}
}
3. 从父组件调用子组件的方法
//Child Component
import {Component} from '@angular/core';
@Component({
selector: '<child-component></child-component>',
template: 'some html here',
})
export class ChildComponent {
constructor() {
}
someMethodOfChildComponentToBeCalled(){
// i am called
}
}
//Parent Component
import {Component, OnInit} from '@angular/core';
import {ChildComponent} from './child.component';
@Component({
selector: '<parent-component></parent-component>',
template: `some html
<child-component>
</child-component>
some html
`
})
export class ParentComponent implements OnInit {
@ViewChild(ChildComponent) private _child:
ChildComponent;
ngOnInit() {
this._child.someMethodOfChildComponentToBeCalled();
}
}
除了这些之外,可能还有其他的交流方式。 :)