![](/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.