網站搜尋

angular - 從子元件到父元件的 EventEmitter 無法運作


我需要將一個值 (0) 傳遞給父組件,所以我如下調用子組件:

<app-componentadduser [target]="target" *ngIf="opt==1" (newItemEvent)="changeOpt($event)"></app-componentadduser>

以及 changeOpt 的程式碼:

changeOpt(newItem: number) {
    console.log(newItem)
    this.opt = newItem;
  }

在孩子這邊,

@Input() target: string;
  @Output() newItemEvent = new EventEmitter<number>();

那麼當一個按鈕被點擊,並且在一個過程發生之後:

this.newItemEvent.emit(0);

從父元件那裡,我甚至嘗試 console.log newItem(值為 0),但 changeOpt 從未被執行。

我不知道我錯過了什麼。我以為 *ngIf 與此有關,但並沒有。

謝謝。

更新:

Console.log 正在拋出這個錯誤:

TypeError: ctx_r9.changeOpt 不是一個函數。(在 'ctx_r9.changeOpt($event)' 中,'ctx_r9.changeOpt' 未定義)

答案#1

既然你只是傳遞一個數字,試試看

(newItemEvent)="opt=$event"

答案#2

首先,我不知道你把 this.newItemEvent.emit(0); 放在哪裡呼叫

所以這個方法可能有問題。你應該在按鈕或某些操作時調用它。一切其他看起來都沒問題,但也許我是眼瞎 :D

無論如何,我用你的輸出創建了 stackBlitz 範例,一切都正常運作。看看吧。

例子