在Angular 7中,你可以使用@ViewChild
装饰器来获取兄弟组件的实例,并在父组件中调用其方法。以下是一个示例解决方法:
首先,在兄弟组件中定义一个公共方法,可以供其他组件调用:
// 兄弟组件
export class BrotherComponent {
// 定义一个公共方法
public doSomething(): void {
console.log('兄弟组件的方法被调用');
}
}
然后,在父组件中使用@ViewChild
装饰器来获取兄弟组件的实例,并在需要的时候调用它的方法:
// 父组件
import { Component, ViewChild } from '@angular/core';
import { BrotherComponent } from '兄弟组件的路径';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
@ViewChild(BrotherComponent) brotherComponent: BrotherComponent;
handleOutputEvent(event: any): void {
// 在需要的时候调用兄弟组件的方法
this.brotherComponent.doSomething();
}
}
在上述示例中,@ViewChild(BrotherComponent) brotherComponent: BrotherComponent;
装饰器将兄弟组件的实例赋值给brotherComponent
变量。然后,在父组件的handleOutputEvent
方法中,你可以通过this.brotherComponent
来访问兄弟组件的公共方法doSomething()
。
这样,当兄弟组件触发outputEvent
事件时,父组件会调用兄弟组件的doSomething()
方法。