[英]Angular2 - call a function from another standalone component. Basically, call function from outside component
我正在一個組件(Component1)中加載另一個包含表單的獨立組件(Component2)。
想象一下,你做了一個表單組件,我想把它集成到我的組件中,並觸發你寫的提交 function,而不需要點擊你的提交按鈕。
此表單上的提交按鈕會觸發 function 來保存數據:
submitData(newUserForm: NgForm)
主組件(Component1)也有一個提交按鈕。 我想要的是從 Component2 中刪除提交按鈕,並在單擊 Component1 中的提交時觸發提交 function。
就像是:
<button type="button" class="submit" (click)="saveData()">{{ Save }}</button>
saveData() {
Component2.submitData(data);
}
ViewChild 不起作用,因為這兩個組件不是同一個組件的一部分。 此外,output 也不起作用。
我必須從 Component2 外部調用 function 有哪些選項?
我希望你能幫忙。
謝謝你。
問候, AG
沒有太多上下文,我認為您需要一項服務來執行此操作。 如果這兩個組件之間沒有關系,為什么要從組件 2 調用 function? 將保存邏輯放入服務中並將其注入您需要的任何組件中。
在此處使用服務
一些服務
private value: Subject<string> = new Subject<string>();
// return the Subject as an Observable in order to be able to subscribe to it
public get theValue(): Observable<string> {
return this.value.asObservable();
}
// set the current value
public set theValue(value: string) {
this.value.next(value);
}
組件 2 TS
constructor(private someService: SomeService){
}
ngOnInit(): void {
// subscribe to the value and refresh the local variable whenever it changes
this.someService.theValue.subscribe( value => {
console.log('Info from Component 1: ' + value;
if (value === 'Saved') {
Component2.submitData(data);
}
});
}
組件 1 TS
constructor(private someService: SomeService){
}
saveData(): void {
this.someService.theValue = 'Saved';
}
這是關於組件交互的,您需要使用服務在兩個不同的組件之間進行通信。 主要是Angular的依賴注入。
只需您可以使用主題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.