,可以通过使用Angular的@ViewChild装饰器来实现。
首先,在sibling1.component.ts中定义一个公共方法myFunction,并使用@ViewChild装饰器来获取sibling2.component的实例。代码示例如下:
import { Component, ViewChild } from '@angular/core';
import { Sibling2Component } from '../sibling2/sibling2.component';
@Component({
selector: 'app-sibling1',
templateUrl: './sibling1.component.html',
styleUrls: ['./sibling1.component.css']
})
export class Sibling1Component {
@ViewChild(Sibling2Component) sibling2: Sibling2Component;
myFunction() {
// 在这里编写你的逻辑代码
console.log('调用了myFunction');
}
callMyFunction() {
this.sibling2.myFunction();
}
}
然后,在sibling2.component.html中添加一个按钮或其他触发事件的元素,并绑定click事件到sibling1.component.ts中的callMyFunction方法。代码示例如下:
<button (click)="callMyFunction()">调用myFunction</button>
这样,当点击按钮时,就会从sibling1.component.ts角度调用sibling2.component中的myFunction方法。
请注意,以上代码示例是基于Angular框架的实现方式,如果你使用的是其他框架或纯JavaScript/TypeScript开发,实现方式可能会有所不同。
企业创新在线学堂
云+社区技术沙龙[第22期]
小程序云开发官方直播课(应用开发实战)
云+社区技术沙龙[第8期]
云+社区技术沙龙[第14期]
腾讯技术开放日
云+社区技术沙龙 [第31期]
serverless days
云+社区技术沙龙[第5期]
领取专属 10元无门槛券
手把手带您无忧上云