[英]Call function from one component from a component Angular
我是 Angular 的初學者。 我一直面臨着從組件調用組件中的方法的問題,它們與它們無關。 我在互聯網上關注了很多教程,但沒有找到解決方案。
所以細節是:有2個不相關的組件。 第一個組件有一個按鈕,如果我單擊該按鈕,來自第一個組件的字符串應該被發送到第二個組件中的一個函數,並且在該函數中它應該將字符串顯示到控制台中。 但我在這里面臨的問題是該函數在我單擊之前只調用一次,它只顯示值“111”,這是默認值。 請幫我
第一個組件:
export class FirstComponent implements OnInit{ constructor(location:Location, private renderer : Renderer2, private element : ElementRef, private router: Router, private httpClient: HttpClient, private servic: MainService) { } clickMe() { this.servic.sendMessage("001"); } }
第二部分:
export class SecondComponent implements OnInit { clickEventSubs:Subscription; constructor(public servic: MainService, private spinner: NgxSpinnerService, private router: Router){} this.clickEventSubs = this.servic.receiveMessage().subscribe(message => { this.toggle(message); }) public toggle(state: string){ console.log(state); } }
共享服務:
@Injectable({ providedIn: 'root' }) export class MainService { private message = new BehaviorSubject<string>("111"); sendMessage(mess:string) { this.message.next(mess); } receiveMessage(): Observable<any> { return this.message.asObservable(); } }
當組件之間的關系是Child > Parent -通過 @viewChild() 共享日期
在第一個組件中,使用 @ViewChild() 並將第二個組件名稱作為參數傳遞 -
@ViewChild(SecondComponent) secondChildView!: SecondComponent;
然后在第一個組件的函數中調用第二個組件的函數——
import {ViewChild} from '@angular/core';
export class FirstComponent implements OnInit{
@ViewChild(SecondComponent) secondChildView!: SecondComponent;
constructor() {}
clickMe() {
this.secondChildView.toggle('001');
}
}
每當您調用 clickMe 函數時,它都會調用第二個組件的切換函數,您將從第一個組件獲取切換函數中的值。
export class SecondComponent implements OnInit {
constructor(){}
public toggle(state: string){
console.log(state);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.