Angular : 子函数发出时不调用父函数

Angular : parent function not called when child emits

我看过很多与此问题相关的主题,但没有找到答案。所以这是我的主题:

我想使用 EventEmitter.emit(value) 将数据从我的子组件传递到我的父组件。

问题是当我 console.log 我的发射器没有发射任何数据(未定义)。 此外,在发出数据时不会调用 Parent 函数。

我试过了:

我根据 Angular 文档和先例主题做了所有事情,但我没有看到我做错了什么。

感谢您的回复和抽出时间。

子组件HTML

<div class="switch-menu">
        <button class="switch-btn" (click)="toggleMovies($event)" [ngClass]="this.showingMovies == 'Movies' ? 'active-button':''" value="Movies">Movies</button>
        <button class="switch-btn" (click)="toggleMovies($event)" [ngClass]="this.showingMovies == 'TV Shows' ? 'active-button':''" value="TV Shows">TV Shows</button>
    </div>

子组件 TS

@Output() eshowingMovies: EventEmitter<string> = new EventEmitter();
showingMovies: "Movies"|"TV Shows" = "Movies";

toggleMovies(_ev: Event): void{
    if (this.showingMovies !== (_ev.target as HTMLInputElement).value){
      this.showingMovies = this.showingMovies == "Movies" ? "TV Shows" : "Movies";
      this.eshowingMovies.emit(this.showingMovies);
    }
  }

父组件HTML

<app-movie-list-find (eshowingMovies)="toggleMovies($event)" ></app-movie-list-find>
<app-show-list-find (eshowingMovies)="toggleMovies($event)" ></app-show-list-find>

我在父 html 文件中有这条错误消息

事件应该是“电影”|“电视节目”类型,但却是一个事件。

(parameter) $event: Event
Argument of type 'Event' is not assignable to parameter of type '"Movies" | "TV Shows"'.
  Type 'Event' is not assignable to type '"TV Shows"'.ngtsc(2345)
find.component.ts(4, 20): Error occurs in the template of component FindComponent.

父组件 TS

showingMovies: "Movies"|"TV Shows" = "Movies";

toggleMovies(event: "Movies"|"TV Shows"): void{
    if (this.showingMovies !== event){
      this.showingMovies = event;
    }
  }

我不清楚您试图通过当前的实现实现什么,但我看不出有什么理由在单击按钮时在您的 child 中传递事件本身。您可以改为执行以下操作:

<div class="switch-menu">
        <button class="switch-btn" (click)="toggleMovies('Movies')" [ngClass]="this.showingMovies == 'Movies' ? 'active-button':''" value="Movies">Movies</button>
        <button class="switch-btn" (click)="toggleMovies('TV Shows')" [ngClass]="this.showingMovies == 'TV Shows' ? 'active-button':''" value="TV Shows">TV Shows</button>
    </div>

然后在你的 child 函数中发出值 -

toggleMovies(category: "Movies" | "TV Shows"): void {
      this.eshowingMovies.emit(category);
    }
  }

应该可以解决您的问题