在Angular 5中,可以使用以下几种方法来调用不同组件的函数:
@Input()
装饰器来接收该输入属性,并在需要调用父组件方法的地方调用该方法。父组件:
@Component({
selector: 'parent-component',
template: `
`
})
export class ParentComponent {
parentMethod() {
console.log('Parent component method called');
}
}
子组件:
@Component({
selector: 'child-component',
template: `
`
})
export class ChildComponent {
@Input() callParentMethod: Function;
callParentMethod() {
this.callParentMethod();
}
}
服务:
@Injectable()
export class SharedService {
sharedMethod() {
console.log('Shared service method called');
}
}
组件:
@Component({
selector: 'component-a',
template: `
`
})
export class ComponentA {
constructor(private sharedService: SharedService) {}
callSharedMethod() {
this.sharedService.sharedMethod();
}
}
@Component({
selector: 'component-b',
template: `
`
})
export class ComponentB {
constructor(private sharedService: SharedService) {}
callSharedMethod() {
this.sharedService.sharedMethod();
}
}
请根据你的具体需求选择合适的方法来调用不同组件的函数。