![](/img/trans.png)
[英]How to call a function in one React component by button click in another component
[英]How to call a function from another component using click event
我想调用另一个与点击无关的组件的 function
服务文件
import { Injectable } from '@angular/core';
@Injectable()
export class ShareDetailsService {
clicked : boolean = false;
constructor() { }
}
组成部分 2
@Component({
selector: 'app-component2',
templateUrl: './component2.component.html',
styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {
constructor(shareDetailsService : ShareDetailsService) { }
ngOnInit() {
if(shareDetailsService.clicked){
console.log("clicked");
}
}
组件 1
@Component({
selector: 'app-component1',
templateUrl: './component1.component.html',
styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {
constructor(shareDetailsService : ShareDetailsService) { }
ngOnInit() {
if(shareDetailsService.clicked){
console.log("clicked");
}
}
someFunction(){
}
组件 1 Html
<div (click)="someFunction()"></div>
当我使用点击事件调用 function 时,它应该调用另一个组件的 function,我创建了一个服务文件,我可以在其中更改 boolean 变量。
我想在 boolean 变量发生变化时调用 function 而不是在 ngOnit() 上调用 function
使用主题订阅它。
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs'
@Injectable()
export class ShareDetailsService {
clicked$ = new Subject();
}
// 任何组件都可以发布和订阅它
@Component({
selector: 'app-component2',
templateUrl: './component2.component.html',
styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {
constructor(shareDetailsService : ShareDetailsService) {
this.sharedDetailsService.clicked$.subscribe(() => console.log('clicked')
}
onClick() {
this.sharedDetailsService.clicked$.next(); // dispatch the click
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.