[英]Angular 9 call function from another component
我有一個組件讓 app-main 我已經在使用它的另一個組件及其事件發射器:
<app-dashboard (dateFrom)=OnDateFrom($event) ></app-dashboard>
在<app-dashboard>
我有一個 function 是這樣的:
@Output() weatherResult= new EventEmitter<any>();
SendWeatherResult(){
this.weatherResult.emit(results);
}
現在我需要在我的組件中調用SendWeatherResult
function
<app-dashboard (dateFrom)=OnDateFrom($event) //here i need to call this function></app-dashboard>
我想在我的應用程序主中調用 SendWeatherResult function
解釋可能更清楚,但也許您需要的是模板變量:
<app-dashboard #appDashboard (dateFrom)=OnDateFrom($event)></app-dashboard>
<button (click)="appDashboard.SendWeatherResult()"> Send weather result</button>
如果要從 component.ts 中使用它,請使用viewChild :
@ViewChild('appDashboard', { static: false }) appDashboard: DashboardComponent;
callSendWeatherResult(): void {
this.appDashboard.SendWeatherResult()
}
go 有幾種方法可以解決這個問題,但是當我需要多個組件能夠在它們之間進行通信和同步數據時,我更喜歡創建一個全局服務。
weather.service.ts - 可以從任何組件訪問的全局服務。
import { Injectable } from "@angular/core";
import { BehaviorSubject, Observable } from "rxjs";
@Injectable({
providedIn: "root"
})
export class WeatherService {
private _weatherResult = new BehaviorSubject<any>(null);
constructor() {
this.methodToPopulateWeatherResult({ todayis: "sunny" });
}
weatherResult$(): Observable<any> {
return this._weatherResult.asObservable();
}
methodToPopulateWeatherResult(report: any): void {
this._weatherResult.next(report);
}
}
app.component.ts - 展示如何使用 Observables 以編程方式訪問天氣結果。
import { Component, OnInit, VERSION } from "@angular/core";
import { distinctUntilChanged } from "rxjs/operators";
import { WeatherService } from "./weather.service";
@Component({
selector: "my-app",
template: `
<h3>Output from app-main</h3>
{{ report | json }}
<app-dashboard></app-dashboard>
`
})
export class AppComponent implements OnInit {
report: any;
constructor(private weather: WeatherService) {}
ngOnInit() {
this.weather
.weatherResult$()
.pipe(distinctUntilChanged())
.subscribe((report: any) => {
// Manipulate the updated weather report
this.report = report;
});
}
}
dashboard.component.ts - 展示如何在模板中直接顯示天氣結果,以及一個按鈕來全局更新天氣結果。
import { Component, OnInit } from "@angular/core";
import { WeatherService } from "../weather.service";
@Component({
selector: "app-dashboard",
template: `
<h3>Output from app-dashboard</h3>
<p>
{{ weather.weatherResult$() | async | json }}
</p>
<button (click)="weather.methodToPopulateWeatherResult({ todayis: 'rainy' })">
Make it Rain
</button>
<button (click)="weather.methodToPopulateWeatherResult({ todayis: 'snowy' })">
Make it Snow
</button>
`
})
export class DashboardComponent {
constructor(public weather: WeatherService) {}
}
我希望我理解你的問題是正確的。
我也是 angular 的新手,但也許這可能有效。
@Input()
SendWeatherResult(){
return results;
}
<app-dashboard (dateFrom)=OnDateFrom($event)
[(SendWeatherResult)]="saveReturnValueHere"></app-dashboard>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.